﻿using BonjourQuotation.DataAccess.Entity_Framework;
using BonjourQuotation.ObjectModel;
using BonjourQuotation.ObjectModel.AccountData;
using BonjourQuotation.ObjectModel.BusinessData;
using BonjourQuotation.ObjectModel.ErrorData;
using BonjourQuotation.ObjectModel.LoggerData;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.SqlServer;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BonjourQuotation.DataAccess.Repositories
{
    public class OperationRepository : IOperationRepository
    {
        private readonly BonDataEntities _context = new BonDataEntities();
        private readonly log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        public OperationHotelGridBData LoadOperationHotels(int PageNum, List<string> UserRegions, string UserName)
        {
            OperationHotelGridBData Hoteldata = new OperationHotelGridBData();
            try
            {
                var Group = _context.tblGroups.AsQueryable();
                var Customer = _context.tblCustomers.AsQueryable();
                var Country = _context.tblCountries.AsQueryable();
                var VendorConfirm = _context.tblVendorConfirms.AsQueryable();
                var Vendor = _context.tblVendors.AsQueryable();
                var QuotaHotel = _context.tblQuotaHotels.AsQueryable();
                InitOperationHotelGridBData(Hoteldata, VendorConfirm, Group, UserName);
                int Count = 0;
                Hoteldata.Rows = InitHotelGridBData(PageNum, Group, Customer, Country, VendorConfirm, Vendor, QuotaHotel, UserRegions, UserName, ref Count);
                Hoteldata.Count = Count;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToMessageAndCompleteStacktrace());
            }
            return Hoteldata;
        }
        public OperationHotelGridBData SaveOperationHotel(OperationHotelGridBData Data, OperationHotelFilterBData FilterData, int PageNum, List<string> UserRegions, string UserName)
        {
            ErrorBInfo Error = new ErrorBInfo();
            using (var transaction = _context.Database.BeginTransaction(IsolationLevel.Serializable))
            {
                try
                {
                    var GroupIds = Data.SaveRows.Select(row => row.GroupID).ToList();
                    var VendorIds = Data.SaveRows.Select(row => row.VendorID).ToList();
                    var NewVendorIds = Data.SaveRows.Select(row => row.NewVendorID).ToList();
                    var ArrDates = Data.SaveRows.Select(row => row.ArrivalDate).ToList();
                    var ChangeGroups = _context.tblGroups.Where(grp => GroupIds.Contains(grp.GroupID)).ToList();
                    var ChangedVendConf = _context.tblVendorConfirms.Where(vndC => VendorIds.Contains(vndC.VendorID) && GroupIds.Contains(vndC.GroupID) && ArrDates.Contains(vndC.ArrivalDate)).ToList();
                    var ChangedVendConfDet = _context.tblVConfirmDetails.Where(VcDet => VendorIds.Contains(VcDet.VendorID) && GroupIds.Contains(VcDet.GroupID) && ArrDates.Contains(VcDet.ArrivalDate)).ToList();
                    var ChangedAmexVendor = _context.tblAuthForms.Where(amex => VendorIds.Contains((int)amex.VendorID) && GroupIds.Contains((int)amex.GroupID) && ArrDates.Contains(amex.ArrivalDate) && amex.Category == null).ToList();
                    var CardTypes = _context.tblCardTypes.Select(cardtype => cardtype).ToList();
                    // check if same arrival date vendor has more rooms that est num of room
                    foreach (var Row in Data.SaveRows)
                    {
                        if (Row.GroupID != 0)
                        {
                            var VendorID = Row.VendorID;
                            if (Row.NewVendorID != null && Row.NewVendorID != Row.VendorID)
                                VendorID = (int)Row.NewVendorID;
                            var amexEdit = ChangedAmexVendor.Where(amex => Row.VendorID == amex.VendorID && Row.GroupID == amex.GroupID && Row.ArrivalDate == amex.ArrivalDate).ToList();
                            if (amexEdit.Any(amex => amex.LineNo == 1))
                            {
                                var amexEditFirst = amexEdit.Where(amex => amex.LineNo == 1).SingleOrDefault();
                                amexEditFirst.AuthAmt = Row.FirstPayment;
                                amexEditFirst.PaymentDate = Row.FirstPaymentDate;
                                amexEditFirst.CardID = CardTypes.Where(card => card.CardTypeCode == Row.FirstPaymentMethod).Select(card => card.CardTypeID).SingleOrDefault();
                                amexEditFirst.VendorID = VendorID;
                            }
                            else
                            {
                                var CardIDToSave = CardTypes.Where(card => card.CardTypeCode == Row.FirstPaymentMethod).Select(card => card.CardTypeID).SingleOrDefault();
                                tblAuthForm NewAmex = new tblAuthForm()
                                {
                                    VendorID = VendorID,
                                    GroupID = Row.GroupID,
                                    CardID = CardIDToSave,
                                    PaymentDate = Row.FirstPaymentDate,
                                    AuthAmt = Row.FirstPayment,
                                    LineNo = 1,
                                    ArrivalDate = Row.ArrivalDate,
                                };
                                _context.tblAuthForms.Add(NewAmex);
                            }
                            if (amexEdit.Any(amex => amex.LineNo == 2))
                            {
                                var amexEditSecond = amexEdit.Where(amex => amex.LineNo == 2).SingleOrDefault();
                                amexEditSecond.AuthAmt = Row.SecondPayment;
                                amexEditSecond.PaymentDate = Row.SecondPaymentDate;
                                amexEditSecond.CardID = CardTypes.Where(card => card.CardTypeCode == Row.SecondPaymentMethod).Select(card => card.CardTypeID).SingleOrDefault();
                                amexEditSecond.VendorID = VendorID;
                            }
                            else
                            {
                                var CardIDToSave = CardTypes.Where(card => card.CardTypeCode == Row.SecondPaymentMethod).Select(card => card.CardTypeID).SingleOrDefault();
                                tblAuthForm NewAmex = new tblAuthForm()
                                {
                                    VendorID = VendorID,
                                    GroupID = Row.GroupID,
                                    CardID = CardIDToSave,
                                    PaymentDate = Row.SecondPaymentDate,
                                    AuthAmt = Row.SecondPayment,
                                    LineNo = 2,
                                    ArrivalDate = Row.ArrivalDate,
                                };
                                _context.tblAuthForms.Add(NewAmex);
                            }
                            if (amexEdit.Any(amex => amex.LineNo == 3))
                            {
                                var amexEditThird = amexEdit.Where(amex => amex.LineNo == 3).SingleOrDefault();
                                amexEditThird.AuthAmt = Row.ThirdPayment;
                                amexEditThird.PaymentDate = Row.ThirdPaymentDate;
                                amexEditThird.CardID = CardTypes.Where(card => card.CardTypeCode == Row.ThirdPaymentMethod).Select(card => card.CardTypeID).SingleOrDefault();
                                amexEditThird.VendorID = VendorID;
                            }
                            else
                            {
                                var CardIDToSave = CardTypes.Where(card => card.CardTypeCode == Row.ThirdPaymentMethod).Select(card => card.CardTypeID).SingleOrDefault();
                                tblAuthForm NewAmex = new tblAuthForm()
                                {
                                    VendorID = VendorID,
                                    GroupID = Row.GroupID,
                                    CardID = CardIDToSave,
                                    PaymentDate = Row.ThirdPaymentDate,
                                    AuthAmt = Row.ThirdPayment,
                                    LineNo = 3,
                                    ArrivalDate = Row.ArrivalDate,
                                };
                                _context.tblAuthForms.Add(NewAmex);
                            }
                        }
                    }
                    foreach (var grp in ChangeGroups)
                    {
                        grp.TechProgUpdt = true;
                        var Row = Data.SaveRows.Where(row => row.GroupID == grp.GroupID).FirstOrDefault();
                        if (Row != null)
                        {
                            grp.StatusID = Row.SelectedGroupStatus;
                            if (Row.SelectedGroupStatus == 4)
                                grp.CanceledInfo = DateTime.Now.ToString("dd/MMM/yy") + " - " + UserName;
                            // Booked Under
                            if (grp.BookedUnder != Row.BookedUnder)
                                grp.BookedUnder = Row.BookedUnder;
                        }
                    }
                    foreach (var Vconf in ChangedVendConf)
                    {
                        var Row = Data.SaveRows.Where(row => row.VendorID == Vconf.VendorID && row.GroupID == Vconf.GroupID && row.ArrivalDate == Vconf.ArrivalDate).FirstOrDefault();
                        // VconfDetail change Sgl.Dbl, etc prices
                        //SGL
                        var VendConfDetSGL = ChangedVendConfDet.Where(ConfDet => ConfDet.VendorID == Vconf.VendorID && ConfDet.GroupID == Vconf.GroupID && ConfDet.ArrivalDate == Vconf.ArrivalDate && ConfDet.ServiceID == 1 && ConfDet.ManualFlg != true).ToList();
                        if (VendConfDetSGL.Count > 0)
                            foreach (var VConfdet in VendConfDetSGL)
                                VConfdet.Price = Row.SingleAmount;
                        //DBL
                        var VendConfDetDGL = ChangedVendConfDet.Where(ConfDet => ConfDet.VendorID == Vconf.VendorID && ConfDet.GroupID == Vconf.GroupID && ConfDet.ArrivalDate == Vconf.ArrivalDate && ConfDet.ServiceID == 2 && ConfDet.ManualFlg != true).ToList();
                        if (VendConfDetDGL.Count > 0)
                            foreach (var VConfdet in VendConfDetDGL)
                                VConfdet.Price = Row.DoubleAmount;
                        //TWN
                        var VendConfDetTWN = ChangedVendConfDet.Where(ConfDet => ConfDet.VendorID == Vconf.VendorID && ConfDet.GroupID == Vconf.GroupID && ConfDet.ArrivalDate == Vconf.ArrivalDate && ConfDet.ServiceID == 3 && ConfDet.ManualFlg != true).ToList();
                        if (VendConfDetTWN.Count > 0)
                            foreach (var VConfdet in VendConfDetTWN)
                                VConfdet.Price = Row.TwinAmount;
                        //TRP
                        var VendConfDetTRP = ChangedVendConfDet.Where(ConfDet => ConfDet.VendorID == Vconf.VendorID && ConfDet.GroupID == Vconf.GroupID && ConfDet.ArrivalDate == Vconf.ArrivalDate && ConfDet.ServiceID == 4 && ConfDet.ManualFlg != true).ToList();
                        if (VendConfDetTRP.Count > 0)
                            foreach (var VConfdet in VendConfDetTRP)
                                VConfdet.Price = Row.TripleAmount;
                        //Quad
                        var VendConfDetQuad = ChangedVendConfDet.Where(ConfDet => ConfDet.VendorID == Vconf.VendorID && ConfDet.GroupID == Vconf.GroupID && ConfDet.ArrivalDate == Vconf.ArrivalDate && ConfDet.ServiceID == 5 && ConfDet.ManualFlg != true).ToList();
                        if (VendConfDetQuad.Count > 0)
                            foreach (var VConfdet in VendConfDetQuad)
                                VConfdet.Price = Row.QuadAmount;
                        //Guide
                        var VendConfDetGuide = ChangedVendConfDet.Where(ConfDet => ConfDet.VendorID == Vconf.VendorID && ConfDet.GroupID == Vconf.GroupID && ConfDet.ArrivalDate == Vconf.ArrivalDate && ConfDet.ServiceID == 87 && ConfDet.ManualFlg != true).ToList();
                        if (VendConfDetGuide.Count > 0)
                            foreach (var VConfdet in VendConfDetGuide)
                                VConfdet.Price = Row.GuideAmount;
                        //Driver
                        var VendConfDetDriver = ChangedVendConfDet.Where(ConfDet => ConfDet.VendorID == Vconf.VendorID && ConfDet.GroupID == Vconf.GroupID && ConfDet.ArrivalDate == Vconf.ArrivalDate && ConfDet.ServiceID == 79 && ConfDet.ManualFlg != true).ToList();
                        if (VendConfDetDriver.Count > 0)
                            foreach (var VConfdet in VendConfDetDriver)
                                VConfdet.Price = Row.DriverAmount;
                        // VconfDetail change Lg, ABF, CBF, Lunch, Dinner
                        if ( Convert.ToBoolean(Row.ABFChecked) != Convert.ToBoolean(Vconf.ABFChecked))
                        {
                            var VendConfDetABF = ChangedVendConfDet.Where(ConfDet => ConfDet.VendorID == Vconf.VendorID && ConfDet.GroupID == Vconf.GroupID && ConfDet.ArrivalDate == Vconf.ArrivalDate && ConfDet.ServiceID == 6 && ConfDet.ManualFlg != true).ToList();
                            // Empty Note
                            Vconf.RoomListNotes = "";
                            if(VendConfDetABF.Count > 0)
                            {
                                foreach(var VConfdet in VendConfDetABF)
                                {
                                    if (VConfdet != VendConfDetABF[0])
                                    {
                                        if (Row.ABFChecked == true)
                                        {
                                            VConfdet.Price = Row.ABF;
                                            VConfdet.ProductID = 1;
                                        }
                                        else
                                        {
                                            VConfdet.Price = 0;
                                            VConfdet.ProductID = 0;
                                        }
                                    } 
                                }
                                if (Row.ABFChecked == true)
                                {
                                    var str = GenerateProvideSectionDates(VendConfDetABF, "B");
                                    if (str != null && Vconf.RoomListNotes == "")
                                        Vconf.RoomListNotes += "American Breakfast: " + str;
                                    else if (str != null && Vconf.RoomListNotes != "")
                                        Vconf.RoomListNotes += "\n American Breakfast: " + str;
                                }
                            }
                        }
                        if (Convert.ToBoolean(Row.CBFChecked) != Convert.ToBoolean(Vconf.CBFChecked))
                        {
                            var VendConfDetCBF = ChangedVendConfDet.Where(ConfDet => ConfDet.VendorID == Vconf.VendorID && ConfDet.GroupID == Vconf.GroupID && ConfDet.ArrivalDate == Vconf.ArrivalDate && ConfDet.ServiceID == 7 && ConfDet.ManualFlg != true).ToList();
                            if (VendConfDetCBF.Count > 0)
                            {
                                foreach (var VConfdet in VendConfDetCBF)
                                {
                                    if (VConfdet != VendConfDetCBF[0])
                                    {
                                        if (Row.CBFChecked == true)
                                        {
                                            VConfdet.Price = Row.CBF;
                                            VConfdet.ProductID = 1;
                                        }
                                        else
                                        {
                                            VConfdet.Price = 0;
                                            VConfdet.ProductID = 0;
                                        }
                                    }
                                } 
                                if (Row.CBFChecked == true)
                                {
                                    var str = GenerateProvideSectionDates(VendConfDetCBF, "B");
                                    if (str != null && Vconf.RoomListNotes == "")
                                        Vconf.RoomListNotes += "Continental Breakfast: " + str;
                                    else if (str != null && Vconf.RoomListNotes != "")
                                        Vconf.RoomListNotes += "\n Continental Breakfast: " + str;
                                }
                            }
                        }
                        if (Convert.ToBoolean(Row.LuggageChecked) != Convert.ToBoolean(Vconf.LuggageChecked))
                        {
                            var VendConfDetLg = ChangedVendConfDet.Where(ConfDet => ConfDet.VendorID == Vconf.VendorID && ConfDet.GroupID == Vconf.GroupID && ConfDet.ArrivalDate == Vconf.ArrivalDate && ConfDet.ServiceID == 103 && ConfDet.ManualFlg != true).FirstOrDefault();
                            if (VendConfDetLg != null && Row.LuggageChecked == true)
                            {
                                VendConfDetLg.Price = Row.Luggage;
                            }
                            else if (VendConfDetLg != null && Row.LuggageChecked != true)
                                VendConfDetLg.Price = 0;
                            if (Vconf.RoomListNotes != null)
                            {
                                if (Row.LuggageChecked == true && !Vconf.RoomListNotes.Contains("Provide Luggage R/T Per person"))
                                {
                                    Vconf.PorterageFlag = true;
                                    Vconf.PorterageNotes = "Provide Luggage R/T Per person";
                                }
                            }
                            else
                            {
                                Vconf.PorterageFlag = true;
                                Vconf.PorterageNotes = "Provide Luggage R/T Per person";
                            }
                        }
                        if (Convert.ToBoolean(Row.LunchChecked) != Convert.ToBoolean(Vconf.LunchChecked))
                        {
                            var VendConfDetLunch = ChangedVendConfDet.Where(ConfDet => ConfDet.VendorID == Vconf.VendorID && ConfDet.GroupID == Vconf.GroupID && ConfDet.ArrivalDate == Vconf.ArrivalDate && ConfDet.ServiceID == 70 && ConfDet.ManualFlg != true).ToList();
                            if (VendConfDetLunch.Count > 0)
                            {
                                foreach (var VConfdet in VendConfDetLunch)
                                {
                                    if (Row.LunchChecked == true)
                                    {
                                        VConfdet.Price = Row.Lunch;
                                        VConfdet.ProductID = 1;
                                    }
                                    else
                                    {
                                        VConfdet.Price = 0;
                                        VConfdet.ProductID = 0;
                                    }
                                }   
                                if (Row.LunchChecked == true)
                                {
                                    var str = GenerateProvideSectionDates(VendConfDetLunch, null);
                                    if (str != null && Vconf.RoomListNotes == "")
                                        Vconf.RoomListNotes += "Lunch: " + str;
                                    else if (str != null && Vconf.RoomListNotes != "")
                                        Vconf.RoomListNotes += "\n Lunch: " + str;
                                }
                            }
                        }
                        if (Convert.ToBoolean(Row.DinnerChecked) != Convert.ToBoolean(Vconf.DinnerChecked))
                        {
                            var VendConfDetDinner = ChangedVendConfDet.Where(ConfDet => ConfDet.VendorID == Vconf.VendorID && ConfDet.GroupID == Vconf.GroupID && ConfDet.ArrivalDate == Vconf.ArrivalDate && ConfDet.ServiceID == 71 && ConfDet.ManualFlg != true).ToList();
                            if (VendConfDetDinner.Count > 0)
                            {
                                foreach (var VConfdet in VendConfDetDinner)
                                {
                                    if (Row.DinnerChecked == true)
                                    {
                                        VConfdet.Price = Row.Dinner;
                                        VConfdet.ProductID = 1;
                                    }
                                    else
                                    {
                                        VConfdet.Price = 0;
                                        VConfdet.ProductID = 0;
                                    }
                                }
                                if (Row.DinnerChecked == true)
                                {
                                    var str = GenerateProvideSectionDates(VendConfDetDinner, null);
                                    if (str != null && Vconf.RoomListNotes == "")
                                        Vconf.RoomListNotes += "Dinner: " + str;
                                    else if (str != null && Vconf.RoomListNotes != "")
                                        Vconf.RoomListNotes += "\n Dinner: " + str;
                                }     
                            }
                        }
                        if (Row != null)
                        {
                            Vconf.StatusID = Row.SelectedVendorStatus;
                            Vconf.EmployeeID = Row.EmployeeID;
                            Vconf.ArrivalCity = Row.ArrivalCity;
                            Vconf.AccMemo = Row.AccountingMemo;
                            Vconf.ClBookingCode = Row.ClientBookingCode;
                            Vconf.ExtraCost = Row.ExtraCost;
                            Vconf.RefFromHotel = Row.RefundReceivedHotel;
                            Vconf.TotInvoice = Row.TotalInvoice;
                            Vconf.TotalCharged = Row.TotalCharged;
                            Vconf.FirstPayment = Row.FirstPayment;
                            Vconf.FirstPaymentMethod = Row.FirstPaymentMethod;
                            Vconf.FirstPaymentDate = Row.FirstPaymentDate;
                            Vconf.SecondPayment = Row.SecondPayment;
                            Vconf.SecondPaymentMethod = Row.SecondPaymentMethod;
                            Vconf.SecondPaymentDate = Row.SecondPaymentDate;
                            Vconf.ThirdPayment = Row.ThirdPayment;
                            Vconf.ThirdPaymentMethod = Row.ThirdPaymentMethod;
                            Vconf.ThirdPaymentDate = Row.ThirdPaymentDate;
                            Vconf.CommissionPerc = Row.CommissionPerc;
                            Vconf.CommissionRecAmt = Row.CommissionRecAmt;
                            Vconf.CommissionRecDate = Row.CommissionRecDate;
                            Vconf.CommissionStatus = Row.CommissionStatus;
                            Vconf.CommCheckNum = Row.CommissionCheckNum;
                            Vconf.CommCheckAmt = Row.CommissionCheckAmt;
                            Vconf.Luggage = Row.Luggage;
                            Vconf.ABF = Row.ABF;
                            Vconf.CBF = Row.CBF;
                            Vconf.Lunch = Row.Lunch;
                            Vconf.Dinner = Row.Dinner;
                            Vconf.LuggageChecked = Row.LuggageChecked;
                            Vconf.ABFChecked = Row.ABFChecked;
                            Vconf.CBFChecked = Row.CBFChecked;
                            Vconf.LunchChecked = Row.LunchChecked;
                            Vconf.DinnerChecked = Row.DinnerChecked;
                            Vconf.Tax = Convert.ToDouble(Row.Tax);
                            Vconf.OccTax = Row.OccTax;
                            Vconf.Comp = Row.Comp;
                            Vconf.Notes = Row.Notes;
                            Vconf.Less = (Row.DoubleAmount + Row.Tax / 100 * Row.DoubleAmount + Row.OccTax) * Row.Comp * (Convert.ToDateTime(Vconf.DepartureDate) - Vconf.ArrivalDate).Days;
                         
                            if (Row.NewVendorID != null && Row.VendorID != Row.NewVendorID)
                            {
                                tblVendorConfirm Vc = new tblVendorConfirm
                                {
                                    AccMemo = Vconf.AccMemo,
                                    ArrivalCity = Vconf.ArrivalCity,
                                    ArrivalDate = Vconf.ArrivalDate,
                                    ArrivalTime = Vconf.ArrivalTime,
                                    Baggage = Vconf.Baggage,
                                    ClBookingCode = Vconf.ClBookingCode,
                                    CommCheckAmt = Vconf.CommCheckAmt,
                                    CommCheckNum = Vconf.CommCheckNum,
                                    CommissionPerc = Vconf.CommissionPerc,
                                    CommissionRecAmt = Vconf.CommissionRecAmt,
                                    CommissionRecDate = Vconf.CommissionRecDate,
                                    CommissionStatus = Vconf.CommissionStatus,
                                    ConfirmDate = Vconf.ConfirmDate,
                                    ConfirmedBy = Vconf.ConfirmedBy,
                                    DateIssued = Vconf.DateIssued,
                                    DepartureDate = Vconf.DepartureDate,
                                    DepartureTime = Vconf.DepartureTime,
                                    EmployeeID = Row.EmployeeID,
                                    ExtraCost = Vconf.ExtraCost,
                                    FirstPayment = Vconf.FirstPayment,
                                    FirstPaymentDate = Vconf.FirstPaymentDate,
                                    FirstPaymentMethod = Vconf.FirstPaymentMethod,
                                    Gratuity = Vconf.Gratuity,
                                    GroupID = Vconf.GroupID,
                                    Less = Vconf.Less,
                                    LessARoom = Vconf.LessARoom,
                                    LessNRoom = Vconf.LessNRoom,
                                    Luggage = Vconf.Luggage,
                                    ABF = Vconf.ABF,
                                    CBF = Vconf.CBF,
                                    Lunch = Vconf.Lunch,
                                    Dinner = Vconf.Dinner,
                                    LuggageChecked = Vconf.LuggageChecked,
                                    ABFChecked = Vconf.ABFChecked,
                                    CBFChecked = Vconf.CBFChecked,
                                    LunchChecked = Vconf.LunchChecked,
                                    DinnerChecked = Vconf.DinnerChecked,
                                    Notes = Row.Notes,
                                    OccTax = Vconf.OccTax,
                                    Pax = Vconf.Pax,
                                    PaxPlus = Vconf.PaxPlus,
                                    PorterageFlag = Vconf.PorterageFlag,
                                    PorterageNotes = Vconf.PorterageNotes,
                                    QuotaBrk = Vconf.QuotaBrk,
                                    QuotaCurr = Vconf.QuotaCurr,
                                    QuotaLg = Vconf.QuotaLg,
                                    QuotaNight = Vconf.QuotaNight,
                                    QuotaOccTax = Vconf.QuotaOccTax,
                                    QuotaRoom = Vconf.QuotaRoom,
                                    QuotaTax = Vconf.QuotaTax,
                                    QuotaVendorDesc = Vconf.QuotaVendorDesc,
                                    QuotaVendorID = Vconf.QuotaVendorID,
                                    RefFromHotel = Vconf.RefFromHotel,
                                    RNPManualFlg = Vconf.RNPManualFlg,
                                    RoomListNotes = Vconf.RoomListNotes,
                                    RoomListEditNotes = Vconf.RoomListEditNotes,
                                    Rooms = Vconf.Rooms,
                                    SecondPayment = Vconf.SecondPayment,
                                    SecondPaymentDate = Vconf.SecondPaymentDate,
                                    SecondPaymentMethod = Vconf.SecondPaymentMethod,
                                    Selected = Vconf.Selected,
                                    StatusDate = Vconf.StatusDate,
                                    StatusID = Vconf.StatusID,
                                    Tax = Vconf.Tax,
                                    ThirdPayment = Vconf.ThirdPayment,
                                    ThirdPaymentDate = Vconf.ThirdPaymentDate,
                                    ThirdPaymentMethod = Vconf.ThirdPaymentMethod,
                                    TotInvoice = Vconf.TotInvoice,
                                    TotalCharged = Vconf.TotalCharged,
                                    Tourleader = Vconf.Tourleader,
                                    VendorConfirmFile = Vconf.VendorConfirmFile,
                                    VendorID = (int)Row.NewVendorID,
                                    VendorRef = Vconf.VendorRef,
                                    VInvoice = Vconf.VInvoice,
                                    VKindFurn = Vconf.VKindFurn,
                                    Voucher = Vconf.Voucher,
                                    VWith = Vconf.VWith,
                                    Comp = Row.Comp,
                                };
                                _context.tblVendorConfirms.Remove(Vconf);
                                _context.tblVendorConfirms.Add(Vc);
                            }
                        }
                    }
                    if (Data.SaveRows.Any(row => row.NewVendorID != null && row.VendorID == 0))
                    {
                        var SaveRows = Data.SaveRows.Where(row => row.NewVendorID != null && row.VendorID == 0).ToList();
                        // New Vendor Confirm
                        foreach (var row in SaveRows)
                        {
                            if (row.NewVendorID != null && row.VendorID == 0)
                            {
                                // new Vendor Confirm
                                tblVendorConfirm NewVConf = new tblVendorConfirm()
                                {
                                    GroupID = row.GroupID,
                                    ArrivalDate = Convert.ToDateTime(row.ArrivalDate),
                                    DepartureDate = row.DepartureDate,
                                    VendorID = (int)row.NewVendorID,
                                    ArrivalCity = row.ArrivalCity,
                                    StatusID = row.SelectedVendorStatus,
                                    AccMemo = row.AccountingMemo,
                                    ClBookingCode = row.ClientBookingCode,
                                    ExtraCost = row.ExtraCost,
                                    EmployeeID = row.EmployeeID,
                                    RefFromHotel = row.RefundReceivedHotel,
                                    TotInvoice = row.TotalInvoice,
                                    TotalCharged = row.TotalCharged,
                                    FirstPayment = row.FirstPayment,
                                    FirstPaymentMethod = row.FirstPaymentMethod,
                                    FirstPaymentDate = row.FirstPaymentDate,
                                    SecondPayment = row.SecondPayment,
                                    SecondPaymentMethod = row.SecondPaymentMethod,
                                    SecondPaymentDate = row.SecondPaymentDate,
                                    ThirdPayment = row.ThirdPayment,
                                    ThirdPaymentMethod = row.ThirdPaymentMethod,
                                    ThirdPaymentDate = row.ThirdPaymentDate,
                                    CommissionPerc = row.CommissionPerc,
                                    CommissionRecAmt = row.CommissionRecAmt,
                                    CommissionRecDate = row.CommissionRecDate,
                                    CommissionStatus = row.CommissionStatus,
                                    CommCheckNum = row.CommissionCheckNum,
                                    CommCheckAmt = row.CommissionCheckAmt,
                                    Luggage = row.Luggage,
                                    ABF = row.ABF,
                                    CBF = row.CBF,
                                    Lunch = row.Lunch,
                                    Dinner = row.Dinner,
                                    LuggageChecked = row.LuggageChecked,
                                    ABFChecked = row.ABFChecked,
                                    CBFChecked = row.CBFChecked,
                                    LunchChecked = row.LunchChecked,
                                    DinnerChecked = row.DinnerChecked,
                                    Tax = Convert.ToDouble(row.Tax),
                                    OccTax = row.OccTax,
                                    Comp = row.Comp,
                                    Less = (row.DoubleAmount + row.Tax / 100 * row.DoubleAmount + row.OccTax) * row.Comp * (Convert.ToDateTime(row.DepartureDate) - Convert.ToDateTime(row.ArrivalDate)).Days,
                                    Notes = row.Notes,
                                };
                                _context.tblVendorConfirms.Add(NewVConf);
                            }
                        }
                    }
                    _context.SaveChanges();
                    transaction.Commit();

                    //  InitHotelFilters(FilterData, ref Room, ref Group);
                }
                catch (Exception ex)
                {
                    Error.errorCode = 5643;
                    Error.Message = ex.Message;
                    logger.Error(ex.ToMessageAndCompleteStacktrace());
                    transaction.Rollback();
                }
            }
            return OperationSearchHotel(Data, FilterData, PageNum, UserRegions, UserName);
        }
        public OperationHotelGridBData OperationSearchHotel(OperationHotelGridBData Data, OperationHotelFilterBData FilterData, int PageNum, List<string> UserRegions, string UserName)
        {
            OperationHotelGridBData Hoteldata = new OperationHotelGridBData();
            Hoteldata.Error = new ErrorBInfo();
            try
            {
                var FilterGroup = _context.tblGroups.AsQueryable();
                var FilterCustomer = _context.tblCustomers.AsQueryable();
                var FilterCountry = _context.tblCountries.AsQueryable();
                var FilterVendorConfirm = _context.tblVendorConfirms.AsQueryable();
                var FilterVendor = _context.tblVendors.AsQueryable();
                var FilterQuotaHotel = _context.tblQuotaHotels.AsQueryable();
                
                if (Data.SearchGroupName != null && Data.SearchGroupName.Length > 0)
                    FilterGroup = FilterGroup.Where(grp => grp.GroupName.Contains(Data.SearchGroupName));
                if (Data.SearchGroupCode != null && Data.SearchGroupCode.Length > 0)
                {
                    FilterGroup = FilterGroup.Where(grp => grp.GroupCode.Contains(Data.SearchGroupCode));
                    // Take total Invoice
                    var Grp = _context.tblGroups.Where(grp => grp.GroupCode == Data.SearchGroupCode).SingleOrDefault();
                    if(Grp != null)
                    {
                        if (Grp.IsGir == false)
                        {
                            Hoteldata.TotInv = _context.tblGroupInvoices.Any(Inv => Inv.GroupID == Grp.GroupID && Inv.Currency == "USD") ? _context.tblGroupInvoices.Where(Inv => Inv.GroupID == Grp.GroupID && Inv.Currency == "USD").Sum(Inv => Inv.Price * Inv.Quantity) : (decimal?)null;
                            Hoteldata.TotInvCad = _context.tblGroupInvoices.Any(Inv => Inv.GroupID == Grp.GroupID && Inv.Currency == "CAD") ? _context.tblGroupInvoices.Where(Inv => Inv.GroupID == Grp.GroupID && Inv.Currency == "CAD").Sum(Inv => Inv.Price * Inv.Quantity) : (decimal?)null;
                        }
                        if (Grp.IsGir == true)
                        {
                            Hoteldata.TotInv = _context.tblGirGroupInvoices.Any(Inv => Inv.GroupID == Grp.GroupID && Inv.Currency == "USD") ? _context.tblGirGroupInvoices.Where(Inv => Inv.GroupID == Grp.GroupID && Inv.Currency == "USD").Sum(Inv => Inv.PriceChange * Inv.Quantity) : (decimal?)null;
                            Hoteldata.TotInvCad =_context.tblGirGroupInvoices.Any(Inv => Inv.GroupID == Grp.GroupID && Inv.Currency == "CAD") ? _context.tblGirGroupInvoices.Where(Inv => Inv.GroupID == Grp.GroupID && Inv.Currency == "CAD").Sum(Inv => Inv.PriceChange * Inv.Quantity) : (decimal?)null;
                        }
                    }
                    Hoteldata.SearchGroupCode = Data.SearchGroupCode;
                }
                if (Data.SearchCheckInFromDate != null)
                    FilterVendorConfirm = FilterVendorConfirm.Where(vconf => vconf.ArrivalDate >= Data.SearchCheckInFromDate);
                if (Data.SearchCheckInToDate != null)
                    FilterVendorConfirm = FilterVendorConfirm.Where(vconf => vconf.ArrivalDate <= Data.SearchCheckInToDate);
                if (Data.SearchCheckOutFromDate != null)
                    FilterVendorConfirm = FilterVendorConfirm.Where(vconf => vconf.DepartureDate >= Data.SearchCheckOutFromDate);
                if (Data.SearchEmployeeID != 0)
                    FilterVendorConfirm = FilterVendorConfirm.Where(vconf => vconf.EmployeeID == Data.SearchEmployeeID);
                if (Data.SearchCheckOutToDate != null)
                    FilterVendorConfirm = FilterVendorConfirm.Where(vconf => vconf.DepartureDate <= Data.SearchCheckOutToDate);
                if (Data.SelectedSearchArrivalCity != null)
                    FilterVendorConfirm = FilterVendorConfirm.Where(vconf => vconf.ArrivalCity.Contains(Data.SelectedSearchArrivalCity));
                if (Data.SelectedSearchDepartureCity != null)
                    FilterGroup = FilterGroup.Where(grp => grp.DepartureCity.Contains(Data.SelectedSearchDepartureCity));
                if (Data.SearchCustomer != null && Data.SearchCustomer.Length > 0)
                    FilterCustomer = FilterCustomer.Where(cust => cust.OrganizationName == Data.SearchCustomer);
                if (Data.SelectedSearchNationality != null)
                    FilterCountry = FilterCountry.Where(cntry => cntry.CountryID == Data.SelectedSearchNationality);
                if (Data.SearchVendorName != null && Data.SearchVendorName.Length > 0)
                    FilterVendor = FilterVendor.Where(vend => vend.VendorName == Data.SearchVendorName);
                if (Data.SearchFlightNo != null && Data.SearchFlightNo.Length > 0)
                    FilterGroup = FilterGroup.Where(grp => grp.FlightInfo == Data.SearchFlightNo);
                if (Data.SelectedSearchStatus != null)
                    FilterGroup = FilterGroup.Where(grp => grp.StatusID == Data.SelectedSearchStatus);

                InitOperationHotelGridBData(Hoteldata, FilterVendorConfirm, FilterGroup, UserName);
                OperationHotelFiltersInit(ref FilterGroup, ref FilterVendor, ref FilterVendorConfirm, FilterData);
                int Count = 0;
                Hoteldata.Rows = InitHotelGridBData(PageNum, FilterGroup, FilterCustomer, FilterCountry, FilterVendorConfirm, FilterVendor, FilterQuotaHotel, UserRegions, UserName, ref Count);
                Hoteldata.Count = Count;
            }
            catch (Exception ex)
            {
                Hoteldata.Error.errorCode = 2346;
                Hoteldata.Error.Message = ex.Message;
                logger.Error(ex.ToMessageAndCompleteStacktrace());
            }
            return Hoteldata;
        }
        public OperationAttractionsGridBData OperationSearchAttractions(OperationAttractionsGridBData Data, OperationAttractionsFilterBData FilterData, int PageNum, List<string> UserRegions, string UserName)
        {
            OperationAttractionsGridBData AttractionsData = new OperationAttractionsGridBData();
            AttractionsData.Error = new ErrorBInfo();
            try
            {
                var FilterGroup = _context.tblGroups.AsQueryable();
                var FilterCustomer = _context.tblCustomers.AsQueryable();
                var FilterAttractionsConfirm = _context.tblAttractionsConfirms.AsQueryable();
                var FilterRestaurantsConfirm = _context.tblRestaurantsConfirms.AsQueryable();
                var FilterVendor = _context.tblVendors.AsQueryable();


                if (Data.SearchGroupCode != null && Data.SearchGroupCode.Length > 0)
                {
                    FilterGroup = FilterGroup.Where(grp => grp.GroupCode.Contains(Data.SearchGroupCode));
                    AttractionsData.SearchGroupCode = Data.SearchGroupCode;
                }
                if (Data.SearchGroupName != null && Data.SearchGroupName.Length > 0)
                    FilterGroup = FilterGroup.Where(grp => grp.GroupName.Contains(Data.SearchGroupName));
                if (Data.SearchVendorName != null && Data.SearchVendorName.Length > 0)
                    FilterVendor = FilterVendor.Where(vnd => vnd.VendorName.Contains(Data.SearchVendorName));
                if (Data.SearchStartFromDate != null)
                {
                    FilterAttractionsConfirm = FilterAttractionsConfirm.Where(attconf => attconf.StartDate >= Data.SearchStartFromDate);
                    FilterRestaurantsConfirm = FilterRestaurantsConfirm.Where(restconf => restconf.StartDate >= Data.SearchStartFromDate);
                }
                if (Data.SearchStartToDate != null)
                {
                    FilterAttractionsConfirm = FilterAttractionsConfirm.Where(attconf => attconf.StartDate <= Data.SearchStartToDate);
                    FilterRestaurantsConfirm = FilterRestaurantsConfirm.Where(restconf => restconf.StartDate <= Data.SearchStartToDate);
                }
                if (Data.SearchEmployeeID != 0)
                {
                    FilterAttractionsConfirm = FilterAttractionsConfirm.Where(attconf => attconf.EmployeeID == Data.SearchEmployeeID);
                    FilterRestaurantsConfirm = FilterRestaurantsConfirm.Where(restconf => restconf.EmployeeID == Data.SearchEmployeeID);
                }
                if (Data.SearchCustomer != null && Data.SearchCustomer.Length > 0)
                    FilterCustomer = FilterCustomer.Where(cust => cust.OrganizationName == Data.SearchCustomer);
                InitOperationAttractionsGridBData(AttractionsData, FilterAttractionsConfirm, FilterRestaurantsConfirm, FilterGroup, UserName);
                OperationAttractionsFiltersInit(ref FilterGroup, ref FilterVendor, ref FilterAttractionsConfirm, ref FilterRestaurantsConfirm,  FilterData);
                int AttrCount = 0;
                AttractionsData.Rows = InitAttractionsGridBData(PageNum, FilterGroup, FilterCustomer, FilterRestaurantsConfirm, FilterVendor, FilterAttractionsConfirm, UserRegions, UserName, ref AttrCount);
                AttractionsData.AttrCount = AttrCount;
            }
            catch (Exception ex)
            {
                AttractionsData.Error.errorCode = 2346;
                AttractionsData.Error.Message = ex.Message;
                logger.Error(ex.ToMessageAndCompleteStacktrace());
            }
            return AttractionsData;
        }
        public OperationAttractionsGridBData OperationFilterAttractions(OperationAttractionsGridBData Data, OperationAttractionsFilterBData FilterData, int PageNum, List<string> UserRegions, string UserName)
        {
            OperationAttractionsGridBData AttractionsData = new OperationAttractionsGridBData();
            AttractionsData.Error = new ErrorBInfo();
            try
            {
                var FilterGroup = _context.tblGroups.AsQueryable();
                var FilterCustomer = _context.tblCustomers.AsQueryable();
                var FilterAttractionsConfirm = _context.tblAttractionsConfirms.AsQueryable();
                var FilterRestaurantsConfirm = _context.tblRestaurantsConfirms.AsQueryable();
                var FilterVendor = _context.tblVendors.AsQueryable();


                if (Data.SearchGroupCode != null && Data.SearchGroupCode.Length > 0)
                    FilterGroup = FilterGroup.Where(grp => grp.GroupCode.Contains(Data.SearchGroupCode));
                if (Data.SearchGroupName != null && Data.SearchGroupName.Length > 0)
                    FilterGroup = FilterGroup.Where(grp => grp.GroupName.Contains(Data.SearchGroupName));
                if (Data.SearchVendorName != null && Data.SearchVendorName.Length > 0)
                    FilterVendor = FilterVendor.Where(vnd => vnd.VendorName.Contains(Data.SearchVendorName));
                if (Data.SearchStartFromDate != null)
                {
                    FilterAttractionsConfirm = FilterAttractionsConfirm.Where(attconf => attconf.StartDate >= Data.SearchStartFromDate);
                    FilterRestaurantsConfirm = FilterRestaurantsConfirm.Where(restconf => restconf.StartDate >= Data.SearchStartFromDate);
                }
                if (Data.SearchStartToDate != null)
                {
                    FilterAttractionsConfirm = FilterAttractionsConfirm.Where(attconf => attconf.StartDate <= Data.SearchStartToDate);
                    FilterRestaurantsConfirm = FilterRestaurantsConfirm.Where(restconf => restconf.StartDate <= Data.SearchStartToDate);
                }
                if (Data.SearchCustomer != null && Data.SearchCustomer.Length > 0)
                    FilterCustomer = FilterCustomer.Where(cust => cust.OrganizationName == Data.SearchCustomer);
                if (Data.SearchEmployeeID != 0)
                {
                    FilterAttractionsConfirm = FilterAttractionsConfirm.Where(attconf => attconf.EmployeeID == Data.SearchEmployeeID);
                    FilterRestaurantsConfirm = FilterRestaurantsConfirm.Where(restconf => restconf.EmployeeID == Data.SearchEmployeeID);
                }
                InitOperationAttractionsGridBData(AttractionsData, FilterAttractionsConfirm, FilterRestaurantsConfirm, FilterGroup, UserName);
                OperationAttractionsFiltersInit(ref FilterGroup, ref FilterVendor, ref FilterAttractionsConfirm, ref FilterRestaurantsConfirm, FilterData);
                int AttrCount = 0;
                AttractionsData.Rows = InitAttractionsGridBData(PageNum, FilterGroup, FilterCustomer, FilterRestaurantsConfirm, FilterVendor, FilterAttractionsConfirm, UserRegions, UserName, ref AttrCount);
                AttractionsData.AttrCount = AttrCount;
            }
            catch (Exception ex)
            {
                AttractionsData.Error.errorCode = 2346;
                AttractionsData.Error.Message = ex.Message;
                logger.Error(ex.ToMessageAndCompleteStacktrace());
            }
            return AttractionsData;
        }
        public OperationMiscGridBData OperationSearchMisc(OperationMiscGridBData Data, OperationMiscFilterBData FilterData, int PageNum, List<string> UserRegions, string UserName)
        {
            OperationMiscGridBData MiscData = new OperationMiscGridBData();
            MiscData.Error = new ErrorBInfo();
            try
            {
                var FilterGroup = _context.tblGroups.AsQueryable();
                var FilterCustomer = _context.tblCustomers.AsQueryable();
                var FilterMiscConfirm = _context.tblMiscConfirms.AsQueryable();
                var FilterVendor = _context.tblVendors.AsQueryable();


                if (Data.SearchGroupCode != null && Data.SearchGroupCode.Length > 0)
                {
                    FilterGroup = FilterGroup.Where(grp => grp.GroupCode.Contains(Data.SearchGroupCode));
                    MiscData.SearchGroupCode = Data.SearchGroupCode;
                }
                if (Data.SearchGroupName != null && Data.SearchGroupName.Length > 0)
                    FilterGroup = FilterGroup.Where(grp => grp.GroupName.Contains(Data.SearchGroupName));
                if (Data.SearchVendorName != null && Data.SearchVendorName.Length > 0)
                    FilterVendor = FilterVendor.Where(vnd => vnd.VendorName.Contains(Data.SearchVendorName));
                if (Data.SearchStartFromDate != null)
                    FilterMiscConfirm = FilterMiscConfirm.Where(miscconf => miscconf.StartDate >= Data.SearchStartFromDate);
                if (Data.SearchStartToDate != null)
                    FilterMiscConfirm = FilterMiscConfirm.Where(miscconf => miscconf.StartDate <= Data.SearchStartToDate);
                if (Data.SearchCustomer != null && Data.SearchCustomer.Length > 0)
                    FilterCustomer = FilterCustomer.Where(cust => cust.OrganizationName == Data.SearchCustomer);
                if (Data.SearchEmployeeID != 0)
                    FilterMiscConfirm = FilterMiscConfirm.Where(miscconf => miscconf.EmployeeID == Data.SearchEmployeeID);
                InitOperationMiscGridBData(MiscData, FilterMiscConfirm, FilterGroup, UserName);
                OperationMiscFiltersInit(ref FilterGroup, ref FilterVendor, ref FilterMiscConfirm, FilterData);
                int MiscCount = 0;
                MiscData.Rows = InitMiscGridBData(PageNum, FilterGroup, FilterCustomer, FilterVendor, FilterMiscConfirm, UserRegions, UserName,ref MiscCount);
                MiscData.MiscCount = MiscCount;
            }
            catch (Exception ex)
            {
                MiscData.Error.errorCode = 2346;
                MiscData.Error.Message = ex.Message;
                logger.Error(ex.ToMessageAndCompleteStacktrace());
            }
            return MiscData;
        }
        public OperationMiscGridBData OperationFilterMisc(OperationMiscGridBData Data, OperationMiscFilterBData FilterData, int PageNum, List<string> UserRegions, string UserName)
        {
            OperationMiscGridBData MiscData = new OperationMiscGridBData();
            MiscData.Error = new ErrorBInfo();
            try
            {
                var FilterGroup = _context.tblGroups.AsQueryable();
                var FilterCustomer = _context.tblCustomers.AsQueryable();
                var FilterMiscConfirm = _context.tblMiscConfirms.AsQueryable();
                var FilterVendor = _context.tblVendors.AsQueryable();


                if (Data.SearchGroupCode != null && Data.SearchGroupCode.Length > 0)
                    FilterGroup = FilterGroup.Where(grp => grp.GroupCode.Contains(Data.SearchGroupCode));
                if (Data.SearchGroupName != null && Data.SearchGroupName.Length > 0)
                    FilterGroup = FilterGroup.Where(grp => grp.GroupName.Contains(Data.SearchGroupName));
                if (Data.SearchVendorName != null && Data.SearchVendorName.Length > 0)
                    FilterVendor = FilterVendor.Where(vnd => vnd.VendorName.Contains(Data.SearchVendorName));
                if (Data.SearchStartFromDate != null)
                    FilterMiscConfirm = FilterMiscConfirm.Where(miscconf => miscconf.StartDate >= Data.SearchStartFromDate);
                if (Data.SearchStartToDate != null)
                    FilterMiscConfirm = FilterMiscConfirm.Where(miscconf => miscconf.StartDate <= Data.SearchStartToDate);
                if (Data.SearchEmployeeID != 0)
                    FilterMiscConfirm = FilterMiscConfirm.Where(miscconf => miscconf.EmployeeID == Data.SearchEmployeeID);
                if (Data.SearchCustomer != null && Data.SearchCustomer.Length > 0)
                    FilterCustomer = FilterCustomer.Where(cust => cust.OrganizationName == Data.SearchCustomer);
                if (Data.SearchEmployeeID != 0)
                    FilterMiscConfirm = FilterMiscConfirm.Where(miscconf => miscconf.EmployeeID == Data.SearchEmployeeID);
                InitOperationMiscGridBData(MiscData, FilterMiscConfirm, FilterGroup, UserName);
                OperationMiscFiltersInit(ref FilterGroup, ref FilterVendor, ref FilterMiscConfirm, FilterData);
                int MiscCount = 0;
                MiscData.Rows = InitMiscGridBData(PageNum, FilterGroup, FilterCustomer, FilterVendor, FilterMiscConfirm, UserRegions, UserName,ref MiscCount);
                MiscData.MiscCount = MiscCount;
            }
            catch (Exception ex)
            {
                MiscData.Error.errorCode = 2346;
                MiscData.Error.Message = ex.Message;
                logger.Error(ex.ToMessageAndCompleteStacktrace());
            }
            return MiscData;
        }
        public OperationBusGridBData OperationSearchBus(OperationBusGridBData Data, OperationBusFilterBData FilterData, int PageNum, List<string> UserRegions, string UserName)
        {
            OperationBusGridBData BusData = new OperationBusGridBData();
            BusData.Error = new ErrorBInfo();
            try
            {
                var FilterGroup = _context.tblGroups.AsQueryable();
                var FilterCustomer = _context.tblCustomers.AsQueryable();
                var FilterBusConfirm = _context.tblBusConfirms.AsQueryable();
                var FilterGuideConfirm = _context.tblGuideConfirms.AsQueryable();
                var FilterVendor = _context.tblVendors.AsQueryable();
                var FilterGuide = _context.tblGuides.AsQueryable();


                if (Data.SearchGroupCode != null && Data.SearchGroupCode.Length > 0)
                {
                    FilterGroup = FilterGroup.Where(grp => grp.GroupCode.Contains(Data.SearchGroupCode));
                    BusData.SearchGroupCode = Data.SearchGroupCode;
                }
                if (Data.SearchGroupName != null && Data.SearchGroupName.Length > 0)
                    FilterGroup = FilterGroup.Where(grp => grp.GroupName.Contains(Data.SearchGroupName));
                if (Data.SearchStartFromDate != null)
                {
                    FilterBusConfirm = FilterBusConfirm.Where(busconf => busconf.StartDate >= Data.SearchStartFromDate);
                    FilterGuideConfirm = FilterGuideConfirm.Where(guideconf => guideconf.StartDate >= Data.SearchStartFromDate);
                }
                if (Data.SearchStartToDate != null)
                {
                    FilterBusConfirm = FilterBusConfirm.Where(busconf => busconf.StartDate <= Data.SearchStartToDate);
                    FilterGuideConfirm = FilterGuideConfirm.Where(guideconf => guideconf.StartDate <= Data.SearchStartToDate);
                }
                if (Data.SearchEmployeeID != 0)
                    FilterBusConfirm = FilterBusConfirm.Where(busconf => busconf.EmployeeID == Data.SearchEmployeeID);
                if (Data.SearchCustomer != null && Data.SearchCustomer.Length > 0)
                    FilterCustomer = FilterCustomer.Where(cust => cust.OrganizationName == Data.SearchCustomer);
                if (Data.SearchEndCity != null && Data.SearchEndCity.Length > 0)
                    FilterBusConfirm = FilterBusConfirm.Where(busconf => busconf.EndCity.Contains(Data.SearchEndCity));
                if (Data.SearchStartCity != null && Data.SearchStartCity.Length > 0)
                    FilterBusConfirm = FilterBusConfirm.Where(busconf => busconf.StartCity.Contains(Data.SearchStartCity));
                if (Data.SearchVendorName != null && Data.SearchVendorName.Length > 0)
                    FilterVendor = FilterVendor.Where(vnd => vnd.VendorName.Contains(Data.SearchVendorName));
                if (Data.SearchGuideName != null && Data.SearchGuideName.Length > 0)
                    FilterGuide = FilterGuide.Where(guide => (guide.FirstName + guide.LastName).Contains(Data.SearchGuideName));
                InitOperationBusGridBData(BusData, FilterBusConfirm, FilterGuideConfirm, FilterGroup, UserName);
                OperationBusFiltersInit(ref FilterGroup, ref FilterVendor, ref FilterGuide, ref FilterBusConfirm, ref FilterGuideConfirm, FilterData);
                int BusCount = 0;
                BusData.Rows = InitBusGridBData(PageNum, FilterGroup, FilterCustomer, FilterGuideConfirm, FilterVendor, FilterBusConfirm, UserRegions, UserName, ref BusCount);
                BusData.BusCount = BusCount;
            }
            catch (Exception ex)
            {
                BusData.Error.errorCode = 2346;
                BusData.Error.Message = ex.Message;
                logger.Error(ex.ToMessageAndCompleteStacktrace());
            }
            return BusData;
        }
        public OperationBusGridBData OperationFilterBus(OperationBusGridBData Data, OperationBusFilterBData FilterData, int PageNum, List<string> UserRegions, string UserName)
        {
            OperationBusGridBData BusData = new OperationBusGridBData();
            BusData.Error = new ErrorBInfo();
            try
            {
                var FilterGroup = _context.tblGroups.AsQueryable();
                var FilterCustomer = _context.tblCustomers.AsQueryable();
                var FilterBusConfirm = _context.tblBusConfirms.AsQueryable();
                var FilterGuideConfirm = _context.tblGuideConfirms.AsQueryable();
                var FilterVendor = _context.tblVendors.AsQueryable();
                var FilterGuide = _context.tblGuides.AsQueryable();


                if (Data.SearchGroupCode != null && Data.SearchGroupCode.Length > 0)
                    FilterGroup = FilterGroup.Where(grp => grp.GroupCode.Contains(Data.SearchGroupCode));
                if (Data.SearchGroupName != null && Data.SearchGroupName.Length > 0)
                    FilterGroup = FilterGroup.Where(grp => grp.GroupName.Contains(Data.SearchGroupName));
                if (Data.SearchStartFromDate != null)
                {
                    FilterBusConfirm = FilterBusConfirm.Where(busconf => busconf.StartDate >= Data.SearchStartFromDate);
                    FilterGuideConfirm = FilterGuideConfirm.Where(guideconf => guideconf.StartDate >= Data.SearchStartFromDate);
                }
                if (Data.SearchStartToDate != null)
                {
                    FilterBusConfirm = FilterBusConfirm.Where(busconf => busconf.StartDate <= Data.SearchStartToDate);
                    FilterGuideConfirm = FilterGuideConfirm.Where(guideconf => guideconf.StartDate <= Data.SearchStartToDate);
                }
                if (Data.SearchEmployeeID != 0)
                    FilterBusConfirm = FilterBusConfirm.Where(busconf => busconf.EmployeeID == Data.SearchEmployeeID);
                if (Data.SearchCustomer != null && Data.SearchCustomer.Length > 0)
                    FilterCustomer = FilterCustomer.Where(cust => cust.OrganizationName == Data.SearchCustomer);
                if (Data.SearchEndCity != null && Data.SearchEndCity.Length > 0)
                    FilterBusConfirm = FilterBusConfirm.Where(busconf => busconf.EndCity.Contains(Data.SearchEndCity));
                if (Data.SearchStartCity != null && Data.SearchStartCity.Length > 0)
                    FilterBusConfirm = FilterBusConfirm.Where(busconf => busconf.StartCity.Contains(Data.SearchStartCity));
                if (Data.SearchVendorName != null && Data.SearchVendorName.Length > 0)
                    FilterVendor = FilterVendor.Where(vnd => vnd.VendorName.Contains(Data.SearchVendorName));
                if (Data.SearchGuideName != null && Data.SearchGuideName.Length > 0)
                    FilterGuide = FilterGuide.Where(guide => (guide.FirstName + guide.LastName).Contains(Data.SearchGuideName));
                InitOperationBusGridBData(BusData, FilterBusConfirm, FilterGuideConfirm, FilterGroup, UserName);
                OperationBusFiltersInit(ref FilterGroup, ref FilterVendor, ref FilterGuide, ref FilterBusConfirm, ref FilterGuideConfirm, FilterData);
                int BusCount = 0;
                BusData.Rows = InitBusGridBData(PageNum, FilterGroup, FilterCustomer, FilterGuideConfirm, FilterVendor, FilterBusConfirm, UserRegions, UserName, ref BusCount);
                BusData.BusCount = BusCount;
            }
            catch (Exception ex)
            {
                BusData.Error.errorCode = 2346;
                BusData.Error.Message = ex.Message;
                logger.Error(ex.ToMessageAndCompleteStacktrace());
            }
            return BusData;
        }
        public OperationGroupCheckListGridBData OperationSearchGroupCheckList(OperationGroupCheckListGridBData Data, OperationGroupCheckListFilterBData FilterData, int PageNum, List<string> UserRegions, string UserName)
        {
            OperationGroupCheckListGridBData GroupCheckListData = new OperationGroupCheckListGridBData();
            GroupCheckListData.Error = new ErrorBInfo();
            try
            {
                var FilterGroup = _context.tblGroups.AsQueryable();
                var FilterCustomer = _context.tblCustomers.AsQueryable();
                var FilterBusConfirm = _context.tblBusConfirms.AsQueryable();
                var FilterGuideConfirm = _context.tblGuideConfirms.AsQueryable();
                var FilterVendor = _context.tblVendors.AsQueryable();
                var FilterGuide = _context.tblGuides.AsQueryable();

                if (Data.SearchGroupCode != null && Data.SearchGroupCode.Length > 0)
                    FilterGroup = FilterGroup.Where(grp => grp.GroupCode.Contains(Data.SearchGroupCode));
                if (Data.SearchGroupName != null && Data.SearchGroupName.Length > 0)
                    FilterGroup = FilterGroup.Where(grp => grp.GroupName.Contains(Data.SearchGroupName));
                if (Data.SearchCustomer != null && Data.SearchCustomer.Length > 0)
                    FilterCustomer = FilterCustomer.Where(cust => cust.OrganizationName == Data.SearchCustomer);
                if (Data.SearchSelectedIsGir != null)
                    FilterGroup = FilterGroup.Where(grp => grp.IsGir == Data.SearchSelectedIsGir);
                InitOperationGroupCheckListGridBData(GroupCheckListData, FilterGroup, FilterCustomer, UserName);
                OperationGroupCheckListFiltersInit(ref FilterGroup, FilterData);
                GroupCheckListData.Rows = InitGroupCheckListGridBData(PageNum, FilterGroup, FilterCustomer, UserRegions, UserName);
            }
            catch (Exception ex)
            {
                GroupCheckListData.Error.errorCode = 2346;
                GroupCheckListData.Error.Message = ex.Message;
                logger.Error(ex.ToMessageAndCompleteStacktrace());
            }
            return GroupCheckListData;
        }
        public OperationGroupCheckListGridBData OperationFilterGroupCheckList(OperationGroupCheckListGridBData Data, OperationGroupCheckListFilterBData FilterData, int PageNum, List<string> UserRegions, string UserName)
        {
            OperationGroupCheckListGridBData GroupCheckListData = new OperationGroupCheckListGridBData();
            GroupCheckListData.Error = new ErrorBInfo();
            try
            {
                var FilterGroup = _context.tblGroups.AsQueryable();
                var FilterCustomer = _context.tblCustomers.AsQueryable();
                var FilterBusConfirm = _context.tblBusConfirms.AsQueryable();
                var FilterGuideConfirm = _context.tblGuideConfirms.AsQueryable();
                var FilterVendor = _context.tblVendors.AsQueryable();
                var FilterGuide = _context.tblGuides.AsQueryable();


                if (Data.SearchGroupCode != null && Data.SearchGroupCode.Length > 0)
                    FilterGroup = FilterGroup.Where(grp => grp.GroupCode.Contains(Data.SearchGroupCode));
                if (Data.SearchGroupName != null && Data.SearchGroupName.Length > 0)
                    FilterGroup = FilterGroup.Where(grp => grp.GroupName.Contains(Data.SearchGroupName));
                if (Data.SearchCustomer != null && Data.SearchCustomer.Length > 0)
                    FilterCustomer = FilterCustomer.Where(cust => cust.OrganizationName == Data.SearchCustomer);
                if (Data.SearchSelectedIsGir != null)
                    FilterGroup = FilterGroup.Where(grp => grp.IsGir == Data.SearchSelectedIsGir);
                InitOperationGroupCheckListGridBData(GroupCheckListData, FilterGroup, FilterCustomer, UserName);
                OperationGroupCheckListFiltersInit(ref FilterGroup, FilterData);
                GroupCheckListData.Rows = InitGroupCheckListGridBData(PageNum, FilterGroup, FilterCustomer, UserRegions, UserName);
            }
            catch (Exception ex)
            {
                GroupCheckListData.Error.errorCode = 2346;
                GroupCheckListData.Error.Message = ex.Message;
                logger.Error(ex.ToMessageAndCompleteStacktrace());
            }
            return GroupCheckListData;
        }
        public OperationRoomGridBData LoadOperationRooms(int PageNum, List<string> UserRegions)
        {
            OperationRoomGridBData Roomdata = new OperationRoomGridBData();
            try
            {
                InitOperationRoomGridBData(Roomdata, null, 0);
                var Room = _context.tblGroupRooms.AsQueryable();
                var Group = _context.tblGroups.AsQueryable();
                var Customer = _context.tblCustomers.AsQueryable();

                List<OperationRoomGirGridRowBData> GirRow;
                Roomdata.Rows = InitRoomGridBData(PageNum, Room, Group, Customer, out GirRow, UserRegions);
                Roomdata.GirRows = GirRow;
                if (Group.SingleOrDefault() != null)
                {
                    Roomdata.IsGir = Group.SingleOrDefault().IsGir != null ? Convert.ToBoolean(Group.SingleOrDefault().IsGir) : false;
                    Roomdata.QuotaID = Group.SingleOrDefault().QuotaID;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToMessageAndCompleteStacktrace());
            }
            return Roomdata;
        }
        public OperationRoomGridBData LoadOperationRooms(int PageNum, OperationRoomSearchBData Data, List<string> UserRegions)
        {
            OperationRoomGridBData Roomdata = new OperationRoomGridBData();
            try
            {

                var Room = _context.tblGroupRooms.AsQueryable();
                var Group = _context.tblGroups.AsQueryable();
                var Customer = _context.tblCustomers.AsQueryable();

                // Group Code search
                if (Data.GroupCode != null && Data.GroupCode.Length > 0)
                    Group = Group.Where(grp => grp.GroupCode == Data.GroupCode);
                // Customer search
                else if (Data.CustomerOrgName != null && Data.CustomerOrgName.Length > 0 && Data.CustomerOrgName != "Gir")
                    Customer = Customer.Where(cust => cust.OrganizationName == Data.CustomerOrgName);
                // Group Name search
                else if (Data.GroupName != null && Data.GroupName.Length > 0)
                    Group = Group.Where(grp => grp.GroupName == Data.GroupName);


                List<OperationRoomGirGridRowBData> GirRow;
                Roomdata.Rows = InitRoomGridBData(PageNum, Room, Group, Customer, out GirRow, UserRegions);

                InitOperationRoomGridBData(Roomdata, Data.GroupCode, 0, ref GirRow);
                Roomdata.GirRows = GirRow;
                if (Group.SingleOrDefault() != null)
                {
                    Roomdata.IsGir = Group.SingleOrDefault().IsGir != null ? Convert.ToBoolean(Group.SingleOrDefault().IsGir) : false;
                    Roomdata.QuotaID = Group.SingleOrDefault().QuotaID;
                    Roomdata.GroupID = Group.SingleOrDefault().GroupID;
                }

            }
            catch (Exception ex)
            {
                logger.Error(ex.ToMessageAndCompleteStacktrace());
            }
            return Roomdata;
        }
        public OperationRoomGridBData SaveOperationRooms(OperationRoomGridBData Data, OperationRoomFilterBData FilterData, int PageNum, List<string> UserRegions)
        {
            ErrorBInfo Error = new ErrorBInfo();
            using (var transaction = _context.Database.BeginTransaction(IsolationLevel.Serializable))
            {
                try
                {
                    // invoice
                    List<tblGirGroupInvoice> tblGirGroupInvoicesCad = new List<tblGirGroupInvoice>();
                    var CurrentGroup = _context.tblGroups.Where(grp => grp.GroupID == Data.GroupID).SingleOrDefault();
                    short TotPax = 0;
                    foreach (var row in Data.Rows)
                    {
                        row.NumOfPerson = OperationRoomPaxByServiceId(row.ServiceID);
                        TotPax += row.NumOfPerson;
                        if (CurrentGroup.IsGir == false)
                            row.CustomerID = CurrentGroup.CustomerID;
                    }
                    var AttrConfirm = _context.tblAttractionsConfirms.Where(att=> att.GroupID == Data.GroupID).ToList();
                    var RestConfirm = _context.tblRestaurantsConfirms.Where(rest=> rest.GroupID == Data.GroupID).ToList();
                    var BusConfirm = _context.tblBusConfirms.Where(bus=> bus.GroupID == Data.GroupID).ToList();
                    var MiscConfirm = _context.tblMiscConfirms.Where(misc=> misc.GroupID == Data.GroupID).ToList();

                    foreach(var att in AttrConfirm)
                        att.Pax = TotPax;
                    foreach(var rest in RestConfirm)
                        rest.Pax = TotPax;
                    foreach(var bus in BusConfirm)
                        bus.Pax = TotPax;
                    foreach(var misc in MiscConfirm)
                        misc.Pax = TotPax;
                    var GroupedRows = Data.Rows.Where(row => row.CustomerID != 0).GroupBy(cust => cust.CustomerID).Select(cust => new
                    {
                        customerID = cust.Key,
                        SSupCount = cust.Sum(pax => pax.NumOfPerson == 1 ? 1 : 0),
                        Pax = cust.Sum(pax => pax.NumOfPerson),
                        FullBCount = Convert.ToInt16(cust.Where(Board => Board.FullBoard == true && Board.FullBoardCount > 0).Sum(Board => Board.FullBoardCount))
                    }).ToList();
                    if (CurrentGroup != null && CurrentGroup.IsGir == true)
                    {
                        var CustIds = Data.Rows.Select(row => row.CustomerID).ToList();
                        var ConnectedInvoices = _context.tblGirGroupInvoices.Where(inv => inv.GroupID == Data.GroupID && CustIds.Contains(inv.CustomerID)).ToList();
                        var ConnectedGirDet = _context.tblGirGroupDetails.Where(GirDet => GirDet.GroupID == Data.GroupID && CustIds.Contains(GirDet.CustomerID)).ToList();
                        foreach (var GirDet in ConnectedGirDet)
                        {
                            int LineNo = 0;
                            if (ConnectedInvoices.Any(inv => inv.GroupID == GirDet.GroupID && inv.CustomerID == GirDet.CustomerID))
                                LineNo = ConnectedInvoices.Where(inv => inv.GroupID == GirDet.GroupID && inv.CustomerID == GirDet.CustomerID).Max(inv => inv.LineNo);
                            else
                            {
                                LineNo = 0;
                                GirDet.InvDate = DateTime.Now;
                                GirDet.ProInv = true;
                                tblInvoiceNo InvoiceNo = new tblInvoiceNo() { GroupID = GirDet.GroupID, InvDate = DateTime.Now, InvNo = 0, ProInv = true };
                                //  _context.tblInvoiceNoes.Add(InvoiceNo);
                            }
                            var Row = GroupedRows.Where(row => row.customerID == GirDet.CustomerID).SingleOrDefault();

                            // Pax
                            if (ConnectedInvoices.Any(inv => inv.GroupID == GirDet.GroupID && inv.CustomerID == GirDet.CustomerID && inv.Description.Contains("Per Person")))
                            {
                                var InvPax = ConnectedInvoices.Where(inv => inv.GroupID == GirDet.GroupID && inv.CustomerID == GirDet.CustomerID && inv.Description.Contains("Per Person") && inv.Currency == "USD").FirstOrDefault();
                                if (InvPax != null)
                                {
                                    InvPax.Price = Math.Round(Convert.ToDecimal(GirDet.PricePerPerson));
                                    InvPax.Quantity = Row != null ? Row.Pax : 0;
                                    if (InvPax.DebCre == true && Row != null)
                                        InvPax.Credit = Math.Round(Convert.ToDecimal(GirDet.PricePerPerson)) * Row.Pax;
                                    if (InvPax.DebCre == false && Row != null)
                                        InvPax.Debit = Math.Round(Convert.ToDecimal(GirDet.PricePerPerson)) * Row.Pax;
                                }
                                var InvPaxCad = ConnectedInvoices.Where(inv => inv.GroupID == GirDet.GroupID && inv.CustomerID == GirDet.CustomerID && inv.Description.Contains("Per Person") && inv.Currency == "CAD").FirstOrDefault();
                                if (InvPaxCad != null)
                                {
                                    InvPaxCad.Price = Math.Round(Convert.ToDecimal(GirDet.PricePerPersonCad));
                                    InvPaxCad.Quantity = Row != null ? Row.Pax : 0;
                                    if (InvPaxCad.DebCre == true && Row != null)
                                        InvPaxCad.Credit = Math.Round(Convert.ToDecimal(GirDet.PricePerPersonCad)) * Row.Pax;
                                    if (InvPaxCad.DebCre == false && Row != null)
                                        InvPaxCad.Debit = Math.Round(Convert.ToDecimal(GirDet.PricePerPersonCad)) * Row.Pax;
                                }
                            }
                            else
                            {
                                // new invoice
                                //per person
                                if (Row != null && Row.Pax > 0 && Convert.ToDecimal(GirDet.PricePerPerson) > 0)
                                {
                                    LineNo++;
                                    tblGirGroupInvoice Invoice = new tblGirGroupInvoice()
                                    {
                                        GroupID = GirDet.GroupID,
                                        CustomerID = GirDet.CustomerID,
                                        LineNo = LineNo,
                                        ItemTypeID = 0,
                                        Price = Math.Round(Convert.ToDecimal(GirDet.PricePerPerson)),
                                        PriceChange = Math.Round(Convert.ToDecimal(GirDet.PricePerPerson)),
                                        Quantity = Row != null ? Row.Pax : 0,
                                        Description = "Per Person",
                                        Currency = "USD",
                                        DebCre = false,
                                        Debit = Row != null ? Math.Round(Convert.ToDecimal(GirDet.PricePerPerson)) * Row.Pax : 0,
                                    };
                                    _context.tblGirGroupInvoices.Add(Invoice);
                                }
                                if (Row != null && Row.Pax > 0 && GirDet.PricePerPersonCad != null && GirDet.PricePerPersonCad > 0)
                                {
                                    // LineNo++;
                                    tblGirGroupInvoice InvoiceCad = new tblGirGroupInvoice()
                                    {
                                        GroupID = GirDet.GroupID,
                                        CustomerID = GirDet.CustomerID,
                                        //  LineNo = LineNo,
                                        ItemTypeID = 0,
                                        Price = Math.Round(Convert.ToDecimal(GirDet.PricePerPersonCad)),
                                        PriceChange = Math.Round(Convert.ToDecimal(GirDet.PricePerPersonCad)),
                                        Quantity = Row != null ? Row.Pax : 0,
                                        Description = "Per Person",
                                        Currency = "CAD",
                                        DebCre = false,
                                        Debit = Row != null ? Math.Round(Convert.ToDecimal(GirDet.PricePerPersonCad)) * Row.Pax : 0,
                                    };
                                    tblGirGroupInvoicesCad.Add(InvoiceCad);
                                }
                            }
                            // full board
                            if (ConnectedInvoices.Any(inv => inv.GroupID == GirDet.GroupID && inv.CustomerID == GirDet.CustomerID && inv.Description.Contains("Full Board")))
                            {
                                var InvFBoard = ConnectedInvoices.Where(inv => inv.GroupID == GirDet.GroupID && inv.CustomerID == GirDet.CustomerID && inv.Description.Contains("Full Board") && inv.Currency == "USD").FirstOrDefault();
                                if (InvFBoard != null)
                                {
                                    InvFBoard.Price = Math.Round(Convert.ToDecimal(GirDet.PriceFullBoard));
                                    InvFBoard.Quantity = Row != null ? Row.FullBCount : 0;
                                    if (InvFBoard.DebCre == true && Row != null)
                                        InvFBoard.Credit = Math.Round(Convert.ToDecimal(GirDet.PriceFullBoard)) * Row.FullBCount;
                                    if (InvFBoard.DebCre == false && Row != null)
                                        InvFBoard.Debit = Math.Round(Convert.ToDecimal(GirDet.PriceFullBoard)) * Row.FullBCount;
                                }
                                var InvFBoardCad = ConnectedInvoices.Where(inv => inv.GroupID == GirDet.GroupID && inv.CustomerID == GirDet.CustomerID && inv.Description.Contains("Full Board") && inv.Currency == "CAD").FirstOrDefault();
                                if (InvFBoardCad != null)
                                {
                                    InvFBoardCad.Price = Math.Round(Convert.ToDecimal(GirDet.PriceFullBoardCad));
                                    InvFBoardCad.Quantity = Row != null ? Row.FullBCount : 0;
                                    if (InvFBoardCad.DebCre == true && Row != null)
                                        InvFBoardCad.Credit = Math.Round(Convert.ToDecimal(GirDet.PriceFullBoardCad)) * Row.FullBCount;
                                    if (InvFBoardCad.DebCre == false && Row != null)
                                        InvFBoardCad.Debit = Math.Round(Convert.ToDecimal(GirDet.PriceFullBoardCad)) * Row.FullBCount;
                                }
                            }
                            else
                            {
                                if (Row != null && Row.FullBCount > 0 && Convert.ToDecimal(GirDet.PriceFullBoard) > 0)
                                {
                                    LineNo++;
                                    tblGirGroupInvoice Invoice = new tblGirGroupInvoice()
                                    {
                                        GroupID = GirDet.GroupID,
                                        CustomerID = GirDet.CustomerID,
                                        LineNo = LineNo,
                                        ItemTypeID = 0,
                                        Price = Math.Round(Convert.ToDecimal(GirDet.PriceFullBoard)),
                                        PriceChange = Math.Round(Convert.ToDecimal(GirDet.PriceFullBoard)),
                                        Quantity = Row != null ? Row.FullBCount : 0,
                                        Description = "Full Board",
                                        Currency = "USD",
                                        DebCre = false,
                                        Debit = Row != null ? Math.Round(Convert.ToDecimal(GirDet.PriceFullBoard)) * Row.FullBCount : 0,
                                    };
                                    _context.tblGirGroupInvoices.Add(Invoice);
                                }
                                if (Row != null && Row.FullBCount > 0 && GirDet.PriceFullBoardCad != null && GirDet.PriceFullBoardCad > 0)
                                {
                                    // LineNo++;
                                    tblGirGroupInvoice InvoiceCad = new tblGirGroupInvoice()
                                    {
                                        GroupID = GirDet.GroupID,
                                        CustomerID = GirDet.CustomerID,
                                        // LineNo = LineNo,
                                        ItemTypeID = 0,
                                        Price = Math.Round(Convert.ToDecimal(GirDet.PriceFullBoardCad)),
                                        PriceChange = Math.Round(Convert.ToDecimal(GirDet.PriceFullBoardCad)),
                                        Quantity = Row != null ? Row.FullBCount : 0,
                                        Description = "Full Board",
                                        Currency = "CAD",
                                        DebCre = false,
                                        Debit = Row != null ? Math.Round(Convert.ToDecimal(GirDet.PriceFullBoardCad)) * Row.FullBCount : 0,
                                    };
                                    tblGirGroupInvoicesCad.Add(InvoiceCad);
                                }
                            }
                            // Single Sup
                            if (ConnectedInvoices.Any(inv => inv.GroupID == GirDet.GroupID && inv.CustomerID == GirDet.CustomerID && inv.Description.Contains("Single Supplement")))
                            {
                                var InvSSup = ConnectedInvoices.Where(inv => inv.GroupID == GirDet.GroupID && inv.CustomerID == GirDet.CustomerID && inv.Description.Contains("Single Supplement") && inv.Currency == "USD").FirstOrDefault();
                                if (InvSSup != null)
                                {
                                    InvSSup.Price = Math.Round(Convert.ToDecimal(GirDet.PriceSingleSupp));
                                    InvSSup.Quantity = Row != null ? Row.SSupCount : 0;
                                    if (InvSSup.DebCre == true && Row != null)
                                        InvSSup.Credit = Math.Round(Convert.ToDecimal(GirDet.PriceSingleSupp)) * Row.SSupCount;
                                    if (InvSSup.DebCre == false && Row != null)
                                        InvSSup.Debit = Math.Round(Convert.ToDecimal(GirDet.PriceSingleSupp)) * Row.SSupCount;
                                }
                                var InvSSupCad = ConnectedInvoices.Where(inv => inv.GroupID == GirDet.GroupID && inv.CustomerID == GirDet.CustomerID && inv.Description.Contains("Single Supplement") && inv.Currency == "CAD").FirstOrDefault();
                                if (InvSSupCad != null)
                                {
                                    InvSSupCad.Price = Math.Round(Convert.ToDecimal(GirDet.PriceSingleSuppCad));
                                    InvSSupCad.Quantity = Row != null ? Row.SSupCount : 0;
                                    if (InvSSupCad.DebCre == true && Row != null)
                                        InvSSupCad.Credit = Math.Round(Convert.ToDecimal(GirDet.PriceSingleSuppCad)) * Row.SSupCount;
                                    if (InvSSupCad.DebCre == false && Row != null)
                                        InvSSupCad.Debit = Math.Round(Convert.ToDecimal(GirDet.PriceSingleSuppCad)) * Row.SSupCount;
                                }
                            }
                            else
                            {
                                if (Row != null && Row.SSupCount > 0 && Convert.ToDecimal(GirDet.PriceSingleSupp) > 0)
                                {
                                    LineNo++;
                                    tblGirGroupInvoice Invoice = new tblGirGroupInvoice()
                                    {
                                        GroupID = GirDet.GroupID,
                                        CustomerID = GirDet.CustomerID,
                                        LineNo = LineNo,
                                        ItemTypeID = 0,
                                        Price = Math.Round(Convert.ToDecimal(GirDet.PriceSingleSupp)),
                                        PriceChange = Math.Round(Convert.ToDecimal(GirDet.PriceSingleSupp)),
                                        Quantity = Row != null ? Row.SSupCount : 0,
                                        Description = "Single Supplement",
                                        Currency = "USD",
                                        DebCre = false,
                                        Debit = Row != null ? Math.Round(Convert.ToDecimal(GirDet.PriceSingleSupp)) * Row.SSupCount : 0,
                                    };
                                    _context.tblGirGroupInvoices.Add(Invoice);
                                }
                                if (Row != null && Row.SSupCount > 0 && GirDet.PriceSingleSuppCad != null && GirDet.PriceSingleSuppCad > 0)
                                {
                                    // LineNo++;
                                    tblGirGroupInvoice InvoiceCad = new tblGirGroupInvoice()
                                    {
                                        GroupID = GirDet.GroupID,
                                        CustomerID = GirDet.CustomerID,
                                        //   LineNo = LineNo,
                                        ItemTypeID = 0,
                                        Price = Math.Round(Convert.ToDecimal(GirDet.PriceSingleSuppCad)),
                                        PriceChange = Math.Round(Convert.ToDecimal(GirDet.PriceSingleSuppCad)),
                                        Quantity = Row != null ? Row.SSupCount : 0,
                                        Description = "Single Supplement",
                                        Currency = "CAD",
                                        DebCre = false,
                                        Debit = Row != null ? Math.Round(Convert.ToDecimal(GirDet.PriceSingleSuppCad)) * Row.SSupCount : 0,
                                    };
                                    tblGirGroupInvoicesCad.Add(InvoiceCad);
                                }
                            }
                            foreach (var InvCad in tblGirGroupInvoicesCad)
                            {
                                LineNo++;
                                InvCad.LineNo = LineNo;
                            }

                            _context.tblGirGroupInvoices.AddRange(tblGirGroupInvoicesCad);
                            //  _context.SaveChanges();
                        }
                    }
                    if (CurrentGroup != null && CurrentGroup.IsGir == false)
                    {
                        int LineNo = 0;
                        // Non Gir Invoice
                        var ConnectedInvoices = _context.tblGroupInvoices.Where(inv => inv.GroupID == Data.GroupID).ToList();
                        if (ConnectedInvoices.Any(inv => inv.GroupID == CurrentGroup.GroupID))
                            LineNo = ConnectedInvoices.Where(inv => inv.GroupID == CurrentGroup.GroupID).Max(inv => inv.LineNo);
                        if (ConnectedInvoices.Any(inv => inv.Description == "Per Person" && inv.Currency == "USD"))
                        {
                            var Inv = ConnectedInvoices.Where(inv => inv.Description == "Per Person" && inv.Currency == "USD").FirstOrDefault();
                            Inv.Quantity = GroupedRows.Count() > 0 ? GroupedRows.FirstOrDefault().Pax : 0;
                            Inv.Price = Math.Round(Convert.ToDecimal(PerPersonPriceByPax(Inv.Quantity, "USD", CurrentGroup.QuotaID)));
                            Inv.PriceChange = Inv.Price;
                            if (Inv.DebCre == false)
                                Inv.Debit = Inv.Quantity * Inv.Price;
                            if (Inv.DebCre == true)
                                Inv.Credit = Inv.Quantity * Inv.Price;
                        }
                        else
                        {
                            //new Inv per pers USD
                            int Qty = GroupedRows.Count() > 0 ? GroupedRows.FirstOrDefault().Pax : 0;
                            decimal price = Math.Round(Convert.ToDecimal(PerPersonPriceByPax(Qty, "USD", CurrentGroup.QuotaID)));
                            if (Qty > 0 && price > 0)
                            {
                                LineNo++;
                                tblGroupInvoice Invoice = new tblGroupInvoice()
                                {
                                    GroupID = CurrentGroup.GroupID,
                                    LineNo = LineNo,
                                    ItemTypeID = 0,
                                    Price = price,
                                    PriceChange = price,
                                    Quantity = Qty,
                                    Description = "Per Person",
                                    Currency = "USD",
                                    DebCre = false,
                                    Debit = Qty * price,
                                };
                                _context.tblGroupInvoices.Add(Invoice);
                            }
                        }
                        if (ConnectedInvoices.Any(inv => inv.Description == "Single Supplement" && inv.Currency == "USD"))
                        {
                            var Inv = ConnectedInvoices.Where(inv => inv.Description == "Single Supplement" && inv.Currency == "USD").FirstOrDefault();
                            Inv.Quantity = GroupedRows.Count() > 0 ? GroupedRows.FirstOrDefault().SSupCount : 0;
                            Inv.Price = Math.Round(SingleSupPriceByCurr("USD", CurrentGroup.QuotaID));
                            Inv.PriceChange = Inv.Price;
                            if (Inv.DebCre == false)
                                Inv.Debit = Inv.Quantity * Inv.Price;
                            if (Inv.DebCre == true)
                                Inv.Credit = Inv.Quantity * Inv.Price;
                        }
                        else
                        {
                            //new Inv Sing Sup USD
                            int Qty = GroupedRows.Count() > 0 ? GroupedRows.FirstOrDefault().SSupCount : 0;
                            decimal price = Math.Round(SingleSupPriceByCurr("USD", CurrentGroup.QuotaID));
                            if (Qty > 0 && price > 0)
                            {
                                LineNo++;
                                tblGroupInvoice Invoice = new tblGroupInvoice()
                                {
                                    GroupID = CurrentGroup.GroupID,
                                    LineNo = LineNo,
                                    ItemTypeID = 0,
                                    Price = price,
                                    PriceChange = price,
                                    Quantity = Qty,
                                    Description = "Single Supplement",
                                    Currency = "USD",
                                    DebCre = false,
                                    Debit = Qty * price,
                                };
                                _context.tblGroupInvoices.Add(Invoice);
                            }
                        }
                        if (ConnectedInvoices.Any(inv => inv.Description == "Per Person" && inv.Currency == "CAD"))
                        {
                            var Inv = ConnectedInvoices.Where(inv => inv.Description == "Per Person" && inv.Currency == "CAD").FirstOrDefault();
                            Inv.Quantity = GroupedRows.Count() > 0 ? GroupedRows.FirstOrDefault().Pax : 0;
                            Inv.Price = Math.Round(Convert.ToDecimal(PerPersonPriceByPax(Inv.Quantity, "CAD", CurrentGroup.QuotaID)));
                            Inv.PriceChange = Inv.Price;
                            if (Inv.DebCre == false)
                                Inv.Debit = Inv.Quantity * Inv.Price;
                            if (Inv.DebCre == true)
                                Inv.Credit = Inv.Quantity * Inv.Price;
                        }
                        else
                        {
                            //new Inv per pers CAD
                            int Qty = GroupedRows.Count() > 0 ? GroupedRows.FirstOrDefault().Pax : 0;
                            decimal price = Math.Round(Convert.ToDecimal(PerPersonPriceByPax(Qty, "CAD", CurrentGroup.QuotaID)));
                            if (Qty > 0 && price > 0)
                            {
                                LineNo++;
                                tblGroupInvoice Invoice = new tblGroupInvoice()
                                {
                                    GroupID = CurrentGroup.GroupID,
                                    LineNo = LineNo,
                                    ItemTypeID = 0,
                                    Price = price,
                                    PriceChange = price,
                                    Quantity = Qty,
                                    Description = "Per Person",
                                    Currency = "CAD",
                                    DebCre = false,
                                    Debit = Qty * price,
                                };
                                _context.tblGroupInvoices.Add(Invoice);
                            }
                        }
                        if (ConnectedInvoices.Any(inv => inv.Description == "Single Supplement" && inv.Currency == "CAD"))
                        {
                            var Inv = ConnectedInvoices.Where(inv => inv.Description == "Single Supplement" && inv.Currency == "CAD").FirstOrDefault();
                            Inv.Quantity = GroupedRows.Count() > 0 ? GroupedRows.FirstOrDefault().SSupCount : 0;
                            Inv.Price = Math.Round(SingleSupPriceByCurr("CAD", CurrentGroup.QuotaID));
                            Inv.PriceChange = Inv.Price;
                            if (Inv.DebCre == false)
                                Inv.Debit = Inv.Quantity * Inv.Price;
                            if (Inv.DebCre == true)
                                Inv.Credit = Inv.Quantity * Inv.Price;
                        }
                        else
                        {
                            //new Inv Sing Sup USD
                            int Qty = GroupedRows.Count() > 0 ? GroupedRows.FirstOrDefault().SSupCount : 0;
                            decimal price = Math.Round(SingleSupPriceByCurr("CAD", CurrentGroup.QuotaID));
                            if (Qty > 0 && price > 0)
                            {
                                LineNo++;
                                tblGroupInvoice Invoice = new tblGroupInvoice()
                                {
                                    GroupID = CurrentGroup.GroupID,
                                    LineNo = LineNo,
                                    ItemTypeID = 0,
                                    Price = price,
                                    PriceChange = price,
                                    Quantity = Qty,
                                    Description = "Single Supplement",
                                    Currency = "CAD",
                                    DebCre = false,
                                    Debit = Qty * price,
                                };
                                _context.tblGroupInvoices.Add(Invoice);
                            }
                        }
                    }

                    var LineNos = Data.Rows.Select(row => row.LineNo).ToList();
                    var ChangableRooms = _context.tblGroupRooms.Where(room => room.GroupID == Data.GroupID && LineNos.Contains(room.LineNo)).ToList();
                    var NewRows = Data.Rows.Where(row => row.GroupID == 0 && row.CustomerID != 0 && row.ServiceID != 0).ToList();
                    List<tblVendorConfirm> VendorConfirms = null;
                    List<tblVConfirmRoom> ChangableConfRooms = null;
                    if (CurrentGroup != null)
                    {
                        VendorConfirms = _context.tblVendorConfirms.Where(VConf => VConf.GroupID == CurrentGroup.GroupID).ToList();

                        var VendConfVendorIds = VendorConfirms.Select(Vc => Vc.VendorID).ToList();
                        var VendorConfArrDates = VendorConfirms.Select(Vc => Vc.ArrivalDate).ToList();
                        ChangableConfRooms = _context.tblVConfirmRooms.Where(VRoom => VRoom.GroupID == CurrentGroup.GroupID
                                                && VendConfVendorIds.Contains(VRoom.VendorID) && VendorConfArrDates.Contains(VRoom.ArrivalDate)).ToList();
                        
                        // change existing vendor rooming  
                        foreach (var Croom in ChangableConfRooms)
                        {
                            var RowRoom = Data.Rows.Where(row => row.GroupID == Croom.GroupID && row.LineNo == Croom.LineNo).SingleOrDefault();
                            if (RowRoom != null)
                            {
                                Croom.Names = RowRoom.Names;
                                Croom.Notes = RowRoom.Notes;
                                Croom.ServiceID = RowRoom.ServiceID;
                                Croom.NoOfPerson = OperationRoomPaxByServiceId(RowRoom.ServiceID);
                                Croom.Title = RowRoom.Title;
                            }
                        }
                        // update existing VendorConfirmsDetails
                        var OldConfDet = UpdateVendorConfirmDetails(VendConfVendorIds, CurrentGroup.GroupID, ChangableConfRooms, VendorConfirms);

                        // change master rooming list 
                        foreach (var room in ChangableRooms)
                        {
                            var RowRoom = Data.Rows.Where(row => row.GroupID == room.GroupID && row.LineNo == room.LineNo).SingleOrDefault();
                            if (RowRoom != null)
                            {
                                room.Names = RowRoom.Names;
                                room.Notes = RowRoom.Notes;
                                room.ServiceID = RowRoom.ServiceID;
                                room.NoOfPerson = OperationRoomPaxByServiceId(RowRoom.ServiceID);
                                room.Title = RowRoom.Title;
                                room.CustomerID = RowRoom.CustomerID;
                                room.FullBoard = RowRoom.FullBoard;
                                room.FullBoardCount = RowRoom.FullBoardCount;
                            }

                        }
                        // new row 
                        if (NewRows != null && NewRows.Count > 0)
                        {
                            int LineNo = 0;
                            if (_context.tblGroupRooms.Any(rm => rm.GroupID == Data.GroupID))
                                LineNo = _context.tblGroupRooms.Where(rm => rm.GroupID == Data.GroupID).Max(rm => rm.LineNo);
                            // new master rooming list
                            var RoomingLineNosVendConf = VendorConfirms.GroupBy(Vnd => Vnd.VendorID).Select(Vnd => new { Key = Vnd.Key, Value = 0 }).ToDictionary(o => o.Key, o => o.Value);
                            var RoomingLineNos = ChangableConfRooms.GroupBy(Room => Room.VendorID).Select(Room => new { Key = Room.Key, Value = Room.Max(Rm => Rm.LineNo) }).ToDictionary(o => o.Key, o => o.Value);
                            foreach (var RoomL in RoomingLineNosVendConf)
                                if (!RoomingLineNos.Keys.Contains(RoomL.Key))
                                    RoomingLineNos.Add(RoomL.Key, RoomL.Value);
                            List<tblVConfirmRoom> NewVConfirmRooms = new List<tblVConfirmRoom>();
                            foreach (var row in NewRows)
                            {
                                LineNo++;
                                tblGroupRoom tblRoom = new tblGroupRoom()
                                {
                                    GroupID = Data.GroupID,
                                    LineNo = LineNo,
                                    Names = row.Names,
                                    Notes = row.Notes,
                                    Title = row.Title,
                                    NoOfPersonRoom = row.NumOfPersonRoom,
                                    ServiceID = row.ServiceID,
                                    NoOfPerson = OperationRoomPaxByServiceId(row.ServiceID),
                                    CustomerID = row.CustomerID,
                                    FullBoard = row.FullBoard,
                                    FullBoardCount = row.FullBoardCount,
                                };
                                _context.tblGroupRooms.Add(tblRoom);
                                // new vendor rooming list
                                foreach (var Vc in VendorConfirms)
                                {
                                    RoomingLineNos[Vc.VendorID]++;
                                    tblVConfirmRoom VCroom = new tblVConfirmRoom
                                    {
                                        ArrivalDate = Vc.ArrivalDate,
                                        CheckInDate = Vc.ArrivalDate,
                                        CheckOutDate = Vc.DepartureDate,
                                        VendorID = Vc.VendorID,
                                        GroupID = Vc.GroupID,
                                        LineNo = RoomingLineNos[Vc.VendorID],
                                        Notes = row.Notes,
                                        Names = row.Names,
                                        NoOfPerson = OperationRoomPaxByServiceId(row.ServiceID),
                                        ServiceID = row.ServiceID,
                                        Title = row.Title,
                                    };
                                    NewVConfirmRooms.Add(VCroom);
                                }
                            }
                            _context.tblVConfirmRooms.AddRange(NewVConfirmRooms);
                            var AllConfRooms = new List<tblVConfirmRoom>();
                            AllConfRooms.AddRange(ChangableConfRooms);
                            AllConfRooms.AddRange(NewVConfirmRooms);
                            UpdateVendorConfirmDetailsNew(VendConfVendorIds, CurrentGroup.GroupID, OldConfDet, AllConfRooms, VendorConfirms);
                        }
                        _context.SaveChanges();
                        transaction.Commit();
                    }
                }
                catch (Exception ex)
                {
                    Error.Message = ex.Message;
                    Error.errorCode = 1010;
                    logger.Error(ex.ToMessageAndCompleteStacktrace());
                    transaction.Rollback();
                }
            }
            OperationRoomGridBData Roomdata = new OperationRoomGridBData();
            Roomdata.Error = Error;
            try
            {
                InitOperationRoomGridBData(Roomdata, null, Data.GroupID);
                var Room = _context.tblGroupRooms.AsQueryable();
                var Group = _context.tblGroups.AsQueryable();
                var Customer = _context.tblCustomers.AsQueryable();
                InitRoomFilters(FilterData, ref Room, ref Group);
                List<OperationRoomGirGridRowBData> GirRow;
                Roomdata.Rows = InitRoomGridBData(PageNum, Room, Group, Customer, out GirRow, UserRegions);
                InitOperationRoomGridBData(Roomdata, null, Data.GroupID, ref GirRow);
                Roomdata.GirRows = GirRow;
                if (Group.SingleOrDefault() != null)
                    Roomdata.IsGir = Group.SingleOrDefault().IsGir != null ? Convert.ToBoolean(Group.SingleOrDefault().IsGir) : false;
            }
            catch (Exception ex)
            {
                Roomdata.Error.errorCode = 1023;
                Roomdata.Error.Message = ex.Message;
                logger.Error(ex.ToMessageAndCompleteStacktrace());
            }
            return Roomdata;
        }
        public ErrorBInfo OverWriteOperationRooms(int GroupID)
        {
            ErrorBInfo Error = new ErrorBInfo();
            using (var transaction = _context.Database.BeginTransaction(IsolationLevel.Serializable))
            {
                try
                {
                    var DeletedVendorConfirmRooms = _context.tblVConfirmRooms.Where(vcrooms => vcrooms.GroupID == GroupID).ToList();
                    var VendorConfirmsByGroupID = _context.tblVendorConfirms.Where(vcnf => vcnf.GroupID == GroupID).ToList();
                    var GroupRoomsByGroupID = _context.tblGroupRooms.Where(grooms => grooms.GroupID == GroupID).ToList();
                    _context.tblVConfirmRooms.RemoveRange(DeletedVendorConfirmRooms);
                    var NewConfirmRooms = new List<tblVConfirmRoom>();
                    foreach (var vconf in VendorConfirmsByGroupID)
                    {
                        foreach (var grooms in GroupRoomsByGroupID)
                        {
                            tblVConfirmRoom newroom = new tblVConfirmRoom
                            {
                                GroupID = grooms.GroupID,
                                VendorID = vconf.VendorID,
                                ArrivalDate = vconf.ArrivalDate,
                                LineNo = grooms.LineNo,
                                Names = grooms.Names,
                                Title = grooms.Title,
                                ServiceID = grooms.ServiceID,
                                NoOfPerson = grooms.NoOfPerson,
                                CheckInDate = vconf.ArrivalDate,
                                CheckOutDate = vconf.DepartureDate,
                            };
                            NewConfirmRooms.Add(newroom);  
                        }
                    }
                    _context.tblVConfirmRooms.AddRange(NewConfirmRooms);
                    UpdateVendorConfirmDetails(VendorConfirmsByGroupID.Select(VndC => VndC.VendorID).ToList(), GroupID, NewConfirmRooms, VendorConfirmsByGroupID);
                    _context.SaveChanges();
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    Error.Message = ex.Message;
                    Error.errorCode = 1010;
                    logger.Error(ex.ToMessageAndCompleteStacktrace());
                    transaction.Rollback();
                }
            }
            return Error;
        }
        public ErrorBInfo OverWriteOperationRoomsByVendorID(int GroupID, int VendorID, DateTime ArrivalDate)
        {
            ErrorBInfo Error = new ErrorBInfo();
            using (var transaction = _context.Database.BeginTransaction(IsolationLevel.Serializable))
            {
                try
                {
                    var DeletedVendorConfirmRooms = _context.tblVConfirmRooms.Where(vcrooms => vcrooms.GroupID == GroupID && vcrooms.VendorID == VendorID).ToList();
                    var VendorConfirmByGroupID = _context.tblVendorConfirms.Where(vcnf => vcnf.GroupID == GroupID && vcnf.VendorID == VendorID).SingleOrDefault();
                    var GroupRoomsByGroupID = _context.tblGroupRooms.Where(grooms => grooms.GroupID == GroupID).ToList();
                    _context.tblVConfirmRooms.RemoveRange(DeletedVendorConfirmRooms);
                    var NewVendorConfRoom = new List<tblVConfirmRoom>();
                    if (VendorConfirmByGroupID != null)
                    {
                        foreach (var grooms in GroupRoomsByGroupID)
                        {
                            tblVConfirmRoom newroom = new tblVConfirmRoom
                            {
                                GroupID = grooms.GroupID,
                                VendorID = VendorConfirmByGroupID.VendorID,
                                ArrivalDate = VendorConfirmByGroupID.ArrivalDate,
                                LineNo = grooms.LineNo,
                                Names = grooms.Names,
                                Title = grooms.Title,
                                ServiceID = grooms.ServiceID,
                                NoOfPerson = grooms.NoOfPerson,
                                CheckInDate = VendorConfirmByGroupID.ArrivalDate,
                                CheckOutDate = VendorConfirmByGroupID.DepartureDate,
                            };
                            NewVendorConfRoom.Add(newroom);               
                        }
                    }
                    _context.tblVConfirmRooms.AddRange(NewVendorConfRoom);
                    UpdateVendorConfirmDetail(VendorID, GroupID, ArrivalDate, NewVendorConfRoom);
                    _context.SaveChanges();
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    Error.Message = ex.Message;
                    Error.errorCode = 1010;
                    logger.Error(ex.ToMessageAndCompleteStacktrace());
                    transaction.Rollback();
                }
            }
            return Error;
        }
        public OperationAttractionsGridBData LoadOperationAttractions(int PageNum, List<string> UserRegions, string UserName)
        {
            OperationAttractionsGridBData AttractionsData = new OperationAttractionsGridBData();
            try
            {
                var Group = _context.tblGroups.AsQueryable();
                var Customer = _context.tblCustomers.AsQueryable();
                var Vendor = _context.tblVendors.AsQueryable();
                var AttractionsConfirm = _context.tblAttractionsConfirms.AsQueryable();
                var VendorConfirm = _context.tblVendorConfirms.AsQueryable();
                var RestaurantsConfirm = _context.tblRestaurantsConfirms.AsQueryable();
                InitOperationAttractionsGridBData(AttractionsData, AttractionsConfirm, RestaurantsConfirm, Group, UserName);
                int AttrCount = 0;
                AttractionsData.Rows = InitAttractionsGridBData(PageNum, Group, Customer, RestaurantsConfirm, Vendor, AttractionsConfirm, UserRegions, UserName, ref AttrCount);
                AttractionsData.AttrCount = AttrCount;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToMessageAndCompleteStacktrace());
            }
            return AttractionsData;
        }
        public OperationMiscGridBData LoadOperationMisc(int PageNum, List<string> UserRegions, string UserName)
        {
            OperationMiscGridBData MiscData = new OperationMiscGridBData();
            try
            {
                var Group = _context.tblGroups.AsQueryable();
                var Customer = _context.tblCustomers.AsQueryable();
                var Vendor = _context.tblVendors.AsQueryable();
                var MiscConfirm = _context.tblMiscConfirms.AsQueryable();
                InitOperationMiscGridBData(MiscData, MiscConfirm, Group, UserName);
                int MiscCount = 0;
                MiscData.Rows = InitMiscGridBData(PageNum, Group, Customer, Vendor, MiscConfirm, UserRegions, UserName,ref MiscCount);
                MiscData.MiscCount = MiscCount;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToMessageAndCompleteStacktrace());
            }
            return MiscData;
        }
        public OperationBusGridBData LoadOperationBus(int PageNum, List<string> UserRegions, string UserName)
        {
            OperationBusGridBData BusData = new OperationBusGridBData();
            var Group = _context.tblGroups.AsQueryable();
            var Customer = _context.tblCustomers.AsQueryable();
            var BusConfirm = _context.tblBusConfirms.AsQueryable();
            var GuideConfirm = _context.tblGuideConfirms.AsQueryable();
            var Vendor = _context.tblVendors.AsQueryable();
            InitOperationBusGridBData(BusData, BusConfirm, GuideConfirm, Group, UserName);
            int BusCount = 0;
            BusData.Rows = InitBusGridBData(PageNum, Group, Customer, GuideConfirm, Vendor, BusConfirm, UserRegions, UserName, ref BusCount);
            BusData.BusCount = BusCount;
            return BusData;
        }
        public OperationAttractionsGridBData SaveOperationAttractions(OperationAttractionsGridBData Data, OperationAttractionsFilterBData FilterData, int PageNum, List<string> UserRegions, string UserName)
        {
            ErrorBInfo Error = new ErrorBInfo();
            using (var transaction = _context.Database.BeginTransaction(IsolationLevel.Serializable))
            {
                try
                {
                    var CardTypes = _context.tblCardTypes.Select(cardtype => cardtype).ToList();
                    var VendorIds = Data.SaveRows.Select(row => row.VendorID).ToList();
                    var NewVendorIds = Data.SaveRows.Select(row => row.NewVendorID).ToList();
                    var Vendors = _context.tblVendors.Where(Vnd => VendorIds.Contains(Vnd.VendorID) || NewVendorIds.Contains(Vnd.VendorID)).ToList();
                    var GroupIds = Data.SaveRows.Select(row => row.GroupID).ToList();
                    var AllGroups = _context.tblGroups.Where(grp => GroupIds.Contains(grp.GroupID)).ToList();
                    foreach (var grp in AllGroups)
                        grp.TechProgUpdt = true;
                    var Groups = _context.tblGroups.Where(grp => GroupIds.Contains(grp.GroupID)).Select(grp => new { GroupId = grp.GroupID, IsGir = grp.IsGir }).ToList();
                    var StartDates = Data.SaveRows.Select(row => row.StartDate).ToList();
                    var ChangedAttrConf = _context.tblAttractionsConfirms.Where(attrC => VendorIds.Contains(attrC.VendorID) && GroupIds.Contains(attrC.GroupID) && StartDates.Contains(attrC.StartDate)).ToList();
                    var ChangedRestConf = _context.tblRestaurantsConfirms.Where(restC => VendorIds.Contains(restC.VendorID) && GroupIds.Contains(restC.GroupID) && StartDates.Contains(restC.StartDate)).ToList();
                    var ChangedAmexVendor = _context.tblAuthForms.Where(amex => VendorIds.Contains((int)amex.VendorID) && GroupIds.Contains((int)amex.GroupID) && StartDates.Contains(amex.ArrivalDate)).ToList();
                    var ChangedGirGrpInvoices = _context.tblGirGroupInvoices.Where(Inv => GroupIds.Contains(Inv.GroupID) && VendorIds.Contains((int)Inv.VendorID)).ToList();
                    var ChangedGrpInvoices = _context.tblGroupInvoices.Where(Inv => GroupIds.Contains(Inv.GroupID)).ToList();
                    
                   // var GirGroupDet = _context.tblGirGroupDetails.Where()
                    // check if same arrival date vendor has more rooms that est num of room
                    Dictionary<int, int> LineNoNonGir = new Dictionary<int, int>();
                    foreach (var GrId in Data.SaveRows.GroupBy(row => row.GroupID).Select(row => row.Key).ToList())
                        LineNoNonGir.Add(GrId, 0);
                    foreach (var Row in Data.SaveRows)
                    {
                        var CurrGrp = Groups.Where(grp => grp.GroupId == Row.GroupID).SingleOrDefault();
                        if (CurrGrp != null && CurrGrp.IsGir == true)
                        {
                            // Gir Group Invoice
                            var ChangeGirInv = ChangedGirGrpInvoices.Where(Inv => Inv.GroupID == Row.GroupID && Inv.VendorID == Row.VendorID).ToList();

                        }
                        else
                        {
                            // ad hock Group Invoice
                            var ChangeInv = ChangedGrpInvoices.Any(Inv => Inv.GroupID == Row.GroupID && Inv.VendorID == Row.VendorID) ? ChangedGrpInvoices.Where(Inv => Inv.GroupID == Row.GroupID && Inv.VendorID == Row.VendorID).FirstOrDefault() : null;
                            if (LineNoNonGir[Row.GroupID] == 0)
                                LineNoNonGir[Row.GroupID] = ChangedGrpInvoices.Any(Inv => Inv.GroupID == Row.GroupID) ? ChangedGrpInvoices.Max(Inv => Inv.LineNo) + 1 : 1;
                            if (ChangeInv == null && Row.IsInvoice == true)
                            {
                                // new Invoice
                                int? CurrVId = Row.NewVendorID != null ? Row.NewVendorID : Row.VendorID;
                                var GroupInv = new tblGroupInvoice
                                {
                                    GroupID = Row.GroupID,
                                    VendorID = CurrVId,
                                    Price = (decimal)Row.InvoicePrice,
                                    PriceChange = (decimal)Row.InvoicePrice,
                                    Currency = Row.QuotaCurr,
                                    ItemTypeID = 0,
                                    DebCre = false,
                                    Quantity = (int)Row.Pax,
                                    Debit = (int)Row.Pax * (decimal)Row.InvoicePrice,
                                    LineNo = LineNoNonGir[Row.GroupID],
                                    Description = Vendors.Where(Vnd => Vnd.VendorID == CurrVId).Select(Vnd => Vnd.VendorName).SingleOrDefault(),
                                };
                                _context.tblGroupInvoices.Add(GroupInv);
                                LineNoNonGir[Row.GroupID] = LineNoNonGir[Row.GroupID] + 1;
                            }
                            else if (ChangeInv != null && Row.IsInvoice == true)
                            {
                                ChangeInv.Price = (decimal)Row.InvoicePrice;
                                ChangeInv.PriceChange = (decimal)Row.InvoicePrice;
                                ChangeInv.Quantity = (int)Row.Pax;
                                if (ChangeInv.DebCre == true)
                                    ChangeInv.Credit = (int)Row.Pax * (decimal)Row.InvoicePrice;
                                else
                                    ChangeInv.Debit = (int)Row.Pax * (decimal)Row.InvoicePrice;
                            }
                            else if (ChangeInv != null && Row.IsInvoice == false)
                            {
                                ChangeInv.Price = 0;
                                ChangeInv.PriceChange = 0;
                                ChangeInv.Quantity = 0;
                                if (ChangeInv.DebCre == true)
                                    ChangeInv.Credit = 0;
                                else
                                    ChangeInv.Debit = 0;
                            }  
                        }
                        if (Row.GroupID != 0)
                        {
                            if (Row.NewVendorID == null || Row.NewVendorID == Row.VendorID)
                            {
                                var StartDate = Row.StartDate;
                                if (Row.NewStartDate != null && Row.NewStartDate != Row.StartDate)
                                    StartDate = (DateTime)Row.NewStartDate;
                                var amexEdit = ChangedAmexVendor.Where(amex => Row.VendorID == amex.VendorID && Row.GroupID == amex.GroupID && Row.StartDate == amex.ArrivalDate && Row.OldRestCategory == amex.Category).ToList();
                                if (amexEdit.Any(amex => amex.LineNo == 1))
                                {
                                    var amexEditFirst = amexEdit.Where(amex => amex.LineNo == 1).SingleOrDefault();
                                    amexEditFirst.AuthAmt = Row.FirstPayAmt;
                                    amexEditFirst.PaymentDate = Row.FirstPayDate;
                                    amexEditFirst.CardID = CardTypes.Where(card => card.CardTypeCode == Row.FirstPayMethod).Select(card => card.CardTypeID).SingleOrDefault();
                                    amexEditFirst.Category = Row.RestCategory;
                                    amexEditFirst.ArrivalDate = StartDate;
                                }
                                else
                                {
                                    var CardIDToSave = CardTypes.Where(card => card.CardTypeCode == Row.FirstPayMethod).Select(card => card.CardTypeID).SingleOrDefault();
                                    tblAuthForm NewAmex = new tblAuthForm()
                                    {
                                        VendorID = Row.VendorID,
                                        GroupID = Row.GroupID,
                                        CardID = CardIDToSave,
                                        PaymentDate = Row.FirstPayDate,
                                        AuthAmt = Row.FirstPayAmt,
                                        LineNo = 1,
                                        ArrivalDate = StartDate,
                                        Category = Row.RestCategory,
                                    };
                                    _context.tblAuthForms.Add(NewAmex);
                                }
                                if (amexEdit.Any(amex => amex.LineNo == 2))
                                {
                                    var amexEditSecond = amexEdit.Where(amex => amex.LineNo == 2).SingleOrDefault();
                                    amexEditSecond.AuthAmt = Row.SecondPayAmt;
                                    amexEditSecond.PaymentDate = Row.SecondPayDate;
                                    amexEditSecond.CardID = CardTypes.Where(card => card.CardTypeCode == Row.SecondPayMethod).Select(card => card.CardTypeID).SingleOrDefault();
                                    amexEditSecond.Category = Row.RestCategory;
                                    amexEditSecond.ArrivalDate = StartDate;
                                }
                                else
                                {
                                    var CardIDToSave = CardTypes.Where(card => card.CardTypeCode == Row.SecondPayMethod).Select(card => card.CardTypeID).SingleOrDefault();
                                    tblAuthForm NewAmex = new tblAuthForm()
                                    {
                                        VendorID = Row.VendorID,
                                        GroupID = Row.GroupID,
                                        CardID = CardIDToSave,
                                        PaymentDate = Row.SecondPayDate,
                                        AuthAmt = Row.SecondPayAmt,
                                        LineNo = 2,
                                        ArrivalDate = StartDate,
                                        Category = Row.RestCategory
                                    };
                                    _context.tblAuthForms.Add(NewAmex);
                                }
                                if (amexEdit.Any(amex => amex.LineNo == 3))
                                {
                                    var amexEditThird = amexEdit.Where(amex => amex.LineNo == 3).SingleOrDefault();
                                    amexEditThird.AuthAmt = Row.ThirdPayAmt;
                                    amexEditThird.PaymentDate = Row.ThirdPayDate;
                                    amexEditThird.CardID = CardTypes.Where(card => card.CardTypeCode == Row.ThirdPayMethod).Select(card => card.CardTypeID).SingleOrDefault();
                                    amexEditThird.Category = Row.RestCategory;
                                    amexEditThird.ArrivalDate = StartDate;
                                }
                                else
                                {
                                    var CardIDToSave = CardTypes.Where(card => card.CardTypeCode == Row.ThirdPayMethod).Select(card => card.CardTypeID).SingleOrDefault();
                                    tblAuthForm NewAmex = new tblAuthForm()
                                    {
                                        VendorID = Row.VendorID,
                                        GroupID = Row.GroupID,
                                        CardID = CardIDToSave,
                                        PaymentDate = Row.ThirdPayDate,
                                        AuthAmt = Row.ThirdPayAmt,
                                        LineNo = 3,
                                        ArrivalDate = StartDate,
                                        Category = Row.RestCategory
                                    };
                                    _context.tblAuthForms.Add(NewAmex);
                                }
                            }
                        }
                    }
                    foreach (var Aconf in ChangedAttrConf)
                    {
                        var Row = Data.SaveRows.Where(row => row.VendorID == Aconf.VendorID && row.GroupID == Aconf.GroupID && row.StartDate == Aconf.StartDate && row.OldRestCategory == null).FirstOrDefault();
                        // replacing Vendor (such as find attr to normal attr)
                        if (Row != null && Row.NewVendorID != null && Row.NewVendorID != Row.VendorID)
                        {
                            tblAttractionsConfirm NewAttraction = new tblAttractionsConfirm()
                            {
                                GroupID = Aconf.GroupID,
                                VendorID = (int)Row.NewVendorID,
                                StartDate = (DateTime)Row.StartDate,
                                QuotaRate = Aconf.QuotaRate,
                                QuotaCurr = Aconf.QuotaCurr,
                                FinishDate = Aconf.FinishDate,
                                ConfirmDate = Aconf.ConfirmDate,
                                QuotaVendorID = Aconf.QuotaVendorID,
                                QuotaVendorDesc = Aconf.QuotaVendorDesc,
                                IsGuideInvoice = Row.IsGuideInvoice,
                                GuideInvoicePrice = Row.GuideInvoicePrice,
                                IsInvoice = Row.IsInvoice,
                                InvoicePrice = Row.InvoicePrice,
                                Pax = Row.IsInvoice == true ? Row.Pax : Aconf.Pax,
                                UnitRate = Row.UnitRate,
                                Done = Row.Done,
                                Time = Row.Time,
                                StatusID = Row.SelectedVendorStatus,
                                EmployeeID = Row.EmployeeID,
                                Deposit = Row.Deposit,
                                DepositDate = Row.DepositDate,
                                FinalPayment = Aconf.FinalPayment,
                                DepositAmtPaid = Aconf.DepositAmtPaid,
                                CCChargeAmt = Row.CCChargeAmt,
                                CCMemo = Row.CCMemo,
                                FirstPayment = Row.FirstPayAmt,
                                FirstPaymentMethod = Row.FirstPayMethod,
                                FirstPaymentDate = Row.FirstPayDate,
                                SecondPayment = Row.SecondPayAmt,
                                SecondPaymentMethod = Row.SecondPayMethod,
                                SecondPaymentDate = Row.SecondPayDate,
                                ThirdPayment = Row.ThirdPayAmt,
                                ThirdPaymentMethod = Row.ThirdPayMethod,
                                ThirdPaymentDate = Row.ThirdPayDate,
                                Notes = Aconf.Notes,
                                AttractionsConfirmFile = Aconf.AttractionsConfirmFile,
                            };
                            _context.tblAttractionsConfirms.Remove(Aconf);
                            _context.tblAttractionsConfirms.Add(NewAttraction);
                        }
                        if (Row != null && (Row.NewVendorID == null || Row.NewVendorID == Row.VendorID))
                        {
                            if (Row.IsInvoice == true)
                                Aconf.Pax = Row.Pax;
                            Aconf.ServiceDetID = Row.ServiceID;
                            Aconf.EmployeeID = Row.EmployeeID;
                            Aconf.Done = Row.Done;
                            Aconf.Time = Row.Time;
                            Aconf.Deposit = Row.Deposit;
                            Aconf.IsGuideInvoice = Row.IsGuideInvoice;
                            Aconf.GuideInvoicePrice = Row.GuideInvoicePrice;
                            Aconf.IsInvoice = Row.IsInvoice;
                            Aconf.InvoicePrice = Row.InvoicePrice;
                            Aconf.StatusID = Row.SelectedVendorStatus;
                            Aconf.UnitRate = Row.UnitRate;
                            Aconf.DepositDate = Row.DepositDate;
                            //Aconf.FinalPayment = Row.FinalPayment;
                            //Aconf.DepositAmtPaid = Row.DepositAmtPaid;
                            Aconf.CCChargeAmt = Row.CCChargeAmt;
                            Aconf.CCMemo = Row.CCMemo;
                            Aconf.FirstPayment = Row.FirstPayAmt;
                            Aconf.FirstPaymentMethod = Row.FirstPayMethod;
                            Aconf.FirstPaymentDate = Row.FirstPayDate;
                            Aconf.SecondPayment = Row.SecondPayAmt;
                            Aconf.SecondPaymentMethod = Row.SecondPayMethod;
                            Aconf.SecondPaymentDate = Row.SecondPayDate;
                            Aconf.ThirdPayment = Row.ThirdPayAmt;
                            Aconf.ThirdPaymentMethod = Row.ThirdPayMethod;
                            Aconf.ThirdPaymentDate = Row.ThirdPayDate;
                            if (Row != null && Row.NewStartDate != null && Row.NewStartDate != Row.StartDate)
                            {
                                tblAttractionsConfirm NewAttraction = new tblAttractionsConfirm()
                                {
                                    GroupID = Aconf.GroupID,
                                    VendorID = Row.VendorID,
                                    StartDate = (DateTime)Row.NewStartDate,
                                    QuotaRate = Aconf.QuotaRate,
                                    QuotaCurr = Aconf.QuotaCurr,
                                    FinishDate = Aconf.FinishDate,
                                    ConfirmDate = Aconf.ConfirmDate,
                                    QuotaVendorID = Aconf.QuotaVendorID,
                                    QuotaVendorDesc = Aconf.QuotaVendorDesc,
                                    IsGuideInvoice = Row.IsGuideInvoice,
                                    GuideInvoicePrice = Row.GuideInvoicePrice,
                                    IsInvoice = Row.IsInvoice,
                                    InvoicePrice = Row.InvoicePrice,
                                    Pax = Row.IsInvoice == true ? Row.Pax : Aconf.Pax,
                                    UnitRate = Row.UnitRate,
                                    Done = Row.Done,
                                    Time = Row.Time,
                                    StatusID = Row.SelectedVendorStatus,
                                    EmployeeID = Row.EmployeeID,
                                    Deposit = Row.Deposit,
                                    DepositDate = Row.DepositDate,
                                    FinalPayment = Aconf.FinalPayment,
                                    DepositAmtPaid = Aconf.DepositAmtPaid,
                                    CCChargeAmt = Row.CCChargeAmt,
                                    CCMemo = Row.CCMemo,
                                    FirstPayment = Row.FirstPayAmt,
                                    FirstPaymentMethod = Row.FirstPayMethod,
                                    FirstPaymentDate = Row.FirstPayDate,
                                    SecondPayment = Row.SecondPayAmt,
                                    SecondPaymentMethod = Row.SecondPayMethod,
                                    SecondPaymentDate = Row.SecondPayDate,
                                    ThirdPayment = Row.ThirdPayAmt,
                                    ThirdPaymentMethod = Row.ThirdPayMethod,
                                    ThirdPaymentDate = Row.ThirdPayDate,
                                    Notes = Aconf.Notes,
                                    AttractionsConfirmFile = Aconf.AttractionsConfirmFile,
                                };
                                _context.tblAttractionsConfirms.Remove(Aconf);
                                _context.tblAttractionsConfirms.Add(NewAttraction);
                            }
                        }
                    }
                    foreach (var Rconf in ChangedRestConf)
                    {
                        var Row = Data.SaveRows.Where(row => row.VendorID == Rconf.VendorID && row.GroupID == Rconf.GroupID && row.StartDate == Rconf.StartDate && row.OldRestCategory == Rconf.Category).FirstOrDefault();
                        // replacing rest (such as find rest to normal rest)
                        if (Row != null && Row.NewVendorID != null && Row.NewVendorID != Row.VendorID)
                        {
                            tblRestaurantsConfirm newRestaurant = new tblRestaurantsConfirm()
                            {
                                GroupID = Rconf.GroupID,
                                VendorID = (int)Row.NewVendorID,
                                StartDate = Rconf.StartDate,
                                Category = Row.RestCategory,
                                QuotaRate = Rconf.QuotaRate,
                                QuotaCurr = Rconf.QuotaCurr,
                                FinishDate = Rconf.FinishDate,
                                ConfirmDate = Rconf.ConfirmDate,
                                QuotaVendorID = Rconf.QuotaVendorID,
                                QuotaVendorDesc = Rconf.QuotaVendorDesc,
                                IsGuideInvoice = Row.IsGuideInvoice,
                                GuideInvoicePrice = Row.GuideInvoicePrice,
                                IsInvoice = Row.IsInvoice,
                                InvoicePrice = Row.InvoicePrice,
                                Pax = Row.IsInvoice == true ? Row.Pax : Rconf.Pax,
                                Done = Row.Done,
                                Time = Row.Time,
                                StatusID = Row.SelectedVendorStatus,
                                ServiceID = Row.SelectedVendorRestService,
                                EmployeeID = Row.EmployeeID,
                                Deposit = Row.Deposit,
                                UnitRate = Row.UnitRate,
                                DepositDate = Row.DepositDate,
                                FinalPayment = Rconf.FinalPayment,
                                DepositAmtPaid = Rconf.DepositAmtPaid,
                                CCChargeAmt = Row.CCChargeAmt,
                                CCMemo = Row.CCMemo,
                                FirstPayment = Row.FirstPayAmt,
                                FirstPaymentMethod = Row.FirstPayMethod,
                                FirstPaymentDate = Row.FirstPayDate,
                                SecondPayment = Row.SecondPayAmt,
                                SecondPaymentMethod = Row.SecondPayMethod,
                                SecondPaymentDate = Row.SecondPayDate,
                                ThirdPayment = Row.ThirdPayAmt,
                                ThirdPaymentMethod = Row.ThirdPayMethod,
                                ThirdPaymentDate = Row.ThirdPayDate,
                                Notes = Rconf.Notes,
                                RestaurantsConfirmFile = Rconf.RestaurantsConfirmFile,
                            };
                            _context.tblRestaurantsConfirms.Remove(Rconf);
                            _context.tblRestaurantsConfirms.Add(newRestaurant);
                        }
                        if (Row != null && (Row.NewVendorID == null || Row.NewVendorID == Row.VendorID))
                        {
                            if (Row.IsInvoice == true)
                                Rconf.Pax = Row.Pax;
                            Rconf.Done = Row.Done;
                            Rconf.Time = Row.Time;
                            Rconf.Deposit = Row.Deposit;
                            Rconf.StatusID = Row.SelectedVendorStatus;
                            Rconf.ServiceID = Row.SelectedVendorRestService;
                            Rconf.EmployeeID = Row.EmployeeID;
                            Rconf.UnitRate = Row.UnitRate;
                            Rconf.DepositDate = Row.DepositDate;
                            Rconf.IsGuideInvoice = Row.IsGuideInvoice;
                            Rconf.GuideInvoicePrice = Row.GuideInvoicePrice;
                            Rconf.IsInvoice = Row.IsInvoice;
                            Rconf.InvoicePrice = Row.InvoicePrice;
                            //Rconf.FinalPayment = Row.FinalPayment;
                            //Rconf.DepositAmtPaid = Row.DepositAmtPaid;
                            Rconf.CCChargeAmt = Row.CCChargeAmt;
                            Rconf.CCMemo = Row.CCMemo;
                            Rconf.FirstPayment = Row.FirstPayAmt;
                            Rconf.FirstPaymentMethod = Row.FirstPayMethod;
                            Rconf.FirstPaymentDate = Row.FirstPayDate;
                            Rconf.SecondPayment = Row.SecondPayAmt;
                            Rconf.SecondPaymentMethod = Row.SecondPayMethod;
                            Rconf.SecondPaymentDate = Row.SecondPayDate;
                            Rconf.ThirdPayment = Row.ThirdPayAmt;
                            Rconf.ThirdPaymentMethod = Row.ThirdPayMethod;
                            Rconf.ThirdPaymentDate = Row.ThirdPayDate;
                            if (Row != null &&  Row.NewStartDate != null && Row.NewStartDate != Row.StartDate)
                            {
                                tblRestaurantsConfirm newRestaurant = new tblRestaurantsConfirm()
                                {
                                    GroupID = Rconf.GroupID,
                                    VendorID = Row.VendorID,
                                    StartDate = (DateTime)Row.NewStartDate,
                                    Category = Row.RestCategory,
                                    QuotaRate = Rconf.QuotaRate,
                                    QuotaCurr = Rconf.QuotaCurr,
                                    FinishDate = Rconf.FinishDate,
                                    ConfirmDate = Rconf.ConfirmDate,
                                    QuotaVendorID = Rconf.QuotaVendorID,
                                    QuotaVendorDesc = Rconf.QuotaVendorDesc,
                                    IsGuideInvoice = Row.IsGuideInvoice,
                                    GuideInvoicePrice = Row.GuideInvoicePrice,
                                    IsInvoice = Row.IsInvoice,
                                    InvoicePrice = Row.InvoicePrice,
                                    Pax = Row.IsInvoice == true ? Row.Pax : Rconf.Pax,
                                    Done = Row.Done,
                                    Time = Row.Time,
                                    StatusID = Row.SelectedVendorStatus,
                                    ServiceID = Row.SelectedVendorRestService,
                                    EmployeeID = Row.EmployeeID,
                                    Deposit = Row.Deposit,
                                    UnitRate = Row.UnitRate,
                                    DepositDate = Row.DepositDate,
                                    FinalPayment = Rconf.FinalPayment,
                                    DepositAmtPaid = Rconf.DepositAmtPaid,
                                    CCChargeAmt = Row.CCChargeAmt,
                                    CCMemo = Row.CCMemo,
                                    FirstPayment = Row.FirstPayAmt,
                                    FirstPaymentMethod = Row.FirstPayMethod,
                                    FirstPaymentDate = Row.FirstPayDate,
                                    SecondPayment = Row.SecondPayAmt,
                                    SecondPaymentMethod = Row.SecondPayMethod,
                                    SecondPaymentDate = Row.SecondPayDate,
                                    ThirdPayment = Row.ThirdPayAmt,
                                    ThirdPaymentMethod = Row.ThirdPayMethod,
                                    ThirdPaymentDate = Row.ThirdPayDate,
                                    Notes = Rconf.Notes,
                                    RestaurantsConfirmFile = Rconf.RestaurantsConfirmFile,
                                };
                                _context.tblRestaurantsConfirms.Remove(Rconf);
                                _context.tblRestaurantsConfirms.Add(newRestaurant);
                            }
                            else if (Row != null && Row.OldRestCategory != Row.RestCategory)
                            {
                                tblRestaurantsConfirm newRestaurant = new tblRestaurantsConfirm()
                                {
                                    GroupID = Rconf.GroupID,
                                    VendorID = Rconf.VendorID,
                                    StartDate = Rconf.StartDate,
                                    Category = Row.RestCategory,
                                    QuotaRate = Rconf.QuotaRate,
                                    QuotaCurr = Rconf.QuotaCurr,
                                    FinishDate = Rconf.FinishDate,
                                    ConfirmDate = Rconf.ConfirmDate,
                                    QuotaVendorID = Rconf.QuotaVendorID,
                                    QuotaVendorDesc = Rconf.QuotaVendorDesc,
                                    IsGuideInvoice = Row.IsGuideInvoice,
                                    GuideInvoicePrice = Row.GuideInvoicePrice,
                                    IsInvoice = Row.IsInvoice,
                                    InvoicePrice = Row.InvoicePrice,
                                    Pax = Row.IsInvoice == true ? Row.Pax : Rconf.Pax,
                                    Done = Row.Done,
                                    Time = Row.Time,
                                    StatusID = Row.SelectedVendorStatus,
                                    ServiceID = Row.SelectedVendorRestService,
                                    EmployeeID = Row.EmployeeID,
                                    Deposit = Row.Deposit,
                                    UnitRate = Row.UnitRate,
                                    DepositDate = Row.DepositDate,
                                    FinalPayment = Rconf.FinalPayment,
                                    DepositAmtPaid = Rconf.DepositAmtPaid,
                                    CCChargeAmt = Row.CCChargeAmt,
                                    CCMemo = Row.CCMemo,
                                    FirstPayment = Row.FirstPayAmt,
                                    FirstPaymentMethod = Row.FirstPayMethod,
                                    FirstPaymentDate = Row.FirstPayDate,
                                    SecondPayment = Row.SecondPayAmt,
                                    SecondPaymentMethod = Row.SecondPayMethod,
                                    SecondPaymentDate = Row.SecondPayDate,
                                    ThirdPayment = Row.ThirdPayAmt,
                                    ThirdPaymentMethod = Row.ThirdPayMethod,
                                    ThirdPaymentDate = Row.ThirdPayDate,
                                    Notes = Rconf.Notes,
                                    RestaurantsConfirmFile = Rconf.RestaurantsConfirmFile,
                                };
                                _context.tblRestaurantsConfirms.Remove(Rconf);
                                _context.tblRestaurantsConfirms.Add(newRestaurant);
                            }
                        }
                    }
                    if (Data.SaveRows.Any(row => row.NewVendorID != null && row.VendorID == 0 && row.NewStartDate != null && row.StartDate == null))
                    {
                        var SaveRows = Data.SaveRows.Where(row => row.NewVendorID != null && row.VendorID == 0 && row.NewStartDate != null && row.StartDate == null).ToList();
                        // New Attraction or Restaurant Confirm
                        foreach (var row in SaveRows)
                        {
                            if (row.RestCategory == null)
                            {
                                // new Attraction Confirm
                                tblAttractionsConfirm newAttraction = new tblAttractionsConfirm()
                                {
                                    GroupID = row.GroupID,
                                    VendorID = (int)row.NewVendorID,
                                    StartDate = (DateTime)row.NewStartDate,
                                    Done = row.Done,
                                    Time = row.Time,
                                    StatusID = row.SelectedVendorStatus,
                                    EmployeeID = row.EmployeeID,
                                    Deposit = row.Deposit,
                                    QuotaCurr = row.QuotaCurr,
                                    UnitRate = row.UnitRate,
                                    DepositDate = row.DepositDate,
                                    IsGuideInvoice = row.IsGuideInvoice,
                                    GuideInvoicePrice = row.GuideInvoicePrice,
                                    IsInvoice = row.IsInvoice,
                                    InvoicePrice = row.InvoicePrice,
                                    Pax = row.Pax,
                                    //FinalPayment = row.FinalPayment,
                                    //DepositAmtPaid = row.DepositAmtPaid,
                                    CCChargeAmt = row.CCChargeAmt,
                                    CCMemo = row.CCMemo,
                                    FirstPayment = row.FirstPayAmt,
                                    FirstPaymentMethod = row.FirstPayMethod,
                                    FirstPaymentDate = row.FirstPayDate,
                                    SecondPayment = row.SecondPayAmt,
                                    SecondPaymentMethod = row.SecondPayMethod,
                                    SecondPaymentDate = row.SecondPayDate,
                                    ThirdPayment = row.ThirdPayAmt,
                                    ThirdPaymentMethod = row.ThirdPayMethod,
                                    ThirdPaymentDate = row.ThirdPayDate,
                                };
                                _context.tblAttractionsConfirms.Add(newAttraction);
                            }
                            else
                            {
                                // new Restaurant Confirm
                                tblRestaurantsConfirm newRestaurant = new tblRestaurantsConfirm()
                                {
                                    GroupID = row.GroupID,
                                    VendorID = (int)row.NewVendorID,
                                    StartDate = (DateTime)row.NewStartDate,
                                    Category = row.RestCategory,
                                    QuotaCurr = row.QuotaCurr,
                                    Done = row.Done,
                                    Time = row.Time,
                                    StatusID = row.SelectedVendorStatus,
                                    ServiceID = row.SelectedVendorRestService,
                                    EmployeeID = row.EmployeeID,
                                    Deposit = row.Deposit,
                                    UnitRate = row.UnitRate,
                                    DepositDate = row.DepositDate,
                                    IsGuideInvoice = row.IsGuideInvoice,
                                    GuideInvoicePrice = row.GuideInvoicePrice,
                                    IsInvoice = row.IsInvoice,
                                    InvoicePrice = row.InvoicePrice,
                                    Pax = row.Pax,
                                    //FinalPayment = row.FinalPayment,
                                    //DepositAmtPaid = row.DepositAmtPaid,
                                    CCChargeAmt = row.CCChargeAmt,
                                    CCMemo = row.CCMemo,
                                    FirstPayment = row.FirstPayAmt,
                                    FirstPaymentMethod = row.FirstPayMethod,
                                    FirstPaymentDate = row.FirstPayDate,
                                    SecondPayment = row.SecondPayAmt,
                                    SecondPaymentMethod = row.SecondPayMethod,
                                    SecondPaymentDate = row.SecondPayDate,
                                    ThirdPayment = row.ThirdPayAmt,
                                    ThirdPaymentMethod = row.ThirdPayMethod,
                                    ThirdPaymentDate = row.ThirdPayDate,
                                };
                                _context.tblRestaurantsConfirms.Add(newRestaurant);
                            }
                        }
                    }
                    _context.SaveChanges();
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    Error.errorCode = 5643;
                    Error.Message = ex.Message;
                    logger.Error(ex.ToMessageAndCompleteStacktrace());
                    transaction.Rollback();
                }
            }
            return OperationSearchAttractions(Data, FilterData, PageNum, UserRegions, UserName);
        }
        public OperationMiscGridBData SaveOperationMisc(OperationMiscGridBData Data, OperationMiscFilterBData FilterData, int PageNum, List<string> UserRegions, string UserName)
        {
            ErrorBInfo Error = new ErrorBInfo();
            using (var transaction = _context.Database.BeginTransaction(IsolationLevel.Serializable))
            {
                try
                {
                    var CardTypes = _context.tblCardTypes.Select(cardtype => cardtype).ToList();
                    var VendorIds = Data.SaveRows.Select(row => row.VendorID).ToList();
                    var GroupIds = Data.SaveRows.Select(row => row.GroupID).ToList();
                    var Vendors = _context.tblVendors.Where(Vnd => VendorIds.Contains(Vnd.VendorID)).ToList();
                    var Groups = _context.tblGroups.Where(grp => GroupIds.Contains(grp.GroupID)).ToList();
                    foreach (var grp in Groups)
                        grp.TechProgUpdt = true;
                    var StartDates = Data.SaveRows.Select(row => row.StartDate).ToList();
                    var ChangedMiscConf = _context.tblMiscConfirms.Where(miscC => VendorIds.Contains(miscC.VendorID) && GroupIds.Contains(miscC.GroupID) && StartDates.Contains(miscC.StartDate)).ToList();
                    var ChangedAmexVendor = _context.tblAuthForms.Where(amex => VendorIds.Contains((int)amex.VendorID) && GroupIds.Contains((int)amex.GroupID) && StartDates.Contains(amex.ArrivalDate)).ToList();

                    foreach (var Row in Data.SaveRows)
                    {
                        if (Row.GroupID != 0)
                        {
                            if (Row.NewVendorID == null || Row.NewVendorID == Row.VendorID)
                            {
                                var StartDate = Row.StartDate;
                                if (Row.NewStartDate != null && Row.NewStartDate != Row.StartDate)
                                    StartDate = (DateTime)Row.NewStartDate;
                                var amexEdit = ChangedAmexVendor.Where(amex => Row.VendorID == amex.VendorID && Row.GroupID == amex.GroupID && Row.StartDate == amex.ArrivalDate && null == amex.Category).ToList();
                                if (amexEdit.Any(amex => amex.LineNo == 1))
                                {
                                    var amexEditFirst = amexEdit.Where(amex => amex.LineNo == 1).SingleOrDefault();
                                    amexEditFirst.AuthAmt = Row.FirstPayAmt;
                                    amexEditFirst.PaymentDate = Row.FirstPayDate;
                                    amexEditFirst.CardID = CardTypes.Where(card => card.CardTypeCode == Row.FirstPayMethod).Select(card => card.CardTypeID).SingleOrDefault();
                                    amexEditFirst.Category = null;
                                    amexEditFirst.ArrivalDate = StartDate;
                                }
                                else
                                {
                                    var CardIDToSave = CardTypes.Where(card => card.CardTypeCode == Row.FirstPayMethod).Select(card => card.CardTypeID).SingleOrDefault();
                                    tblAuthForm NewAmex = new tblAuthForm()
                                    {
                                        VendorID = Row.VendorID,
                                        GroupID = Row.GroupID,
                                        CardID = CardIDToSave,
                                        PaymentDate = Row.FirstPayDate,
                                        AuthAmt = Row.FirstPayAmt,
                                        LineNo = 1,
                                        ArrivalDate = StartDate,
                                        Category = null,
                                    };
                                    _context.tblAuthForms.Add(NewAmex);
                                }
                                if (amexEdit.Any(amex => amex.LineNo == 2))
                                {
                                    var amexEditSecond = amexEdit.Where(amex => amex.LineNo == 2).SingleOrDefault();
                                    amexEditSecond.AuthAmt = Row.SecondPayAmt;
                                    amexEditSecond.PaymentDate = Row.SecondPayDate;
                                    amexEditSecond.CardID = CardTypes.Where(card => card.CardTypeCode == Row.SecondPayMethod).Select(card => card.CardTypeID).SingleOrDefault();
                                    amexEditSecond.Category = null;
                                    amexEditSecond.ArrivalDate = StartDate;
                                }
                                else
                                {
                                    var CardIDToSave = CardTypes.Where(card => card.CardTypeCode == Row.SecondPayMethod).Select(card => card.CardTypeID).SingleOrDefault();
                                    tblAuthForm NewAmex = new tblAuthForm()
                                    {
                                        VendorID = Row.VendorID,
                                        GroupID = Row.GroupID,
                                        CardID = CardIDToSave,
                                        PaymentDate = Row.SecondPayDate,
                                        AuthAmt = Row.SecondPayAmt,
                                        LineNo = 2,
                                        ArrivalDate = StartDate,
                                        Category = null,
                                    };
                                    _context.tblAuthForms.Add(NewAmex);
                                }
                                if (amexEdit.Any(amex => amex.LineNo == 3))
                                {
                                    var amexEditThird = amexEdit.Where(amex => amex.LineNo == 3).SingleOrDefault();
                                    amexEditThird.AuthAmt = Row.ThirdPayAmt;
                                    amexEditThird.PaymentDate = Row.ThirdPayDate;
                                    amexEditThird.CardID = CardTypes.Where(card => card.CardTypeCode == Row.ThirdPayMethod).Select(card => card.CardTypeID).SingleOrDefault();
                                    amexEditThird.Category = null;
                                    amexEditThird.ArrivalDate = StartDate;
                                }
                                else
                                {
                                    var CardIDToSave = CardTypes.Where(card => card.CardTypeCode == Row.ThirdPayMethod).Select(card => card.CardTypeID).SingleOrDefault();
                                    tblAuthForm NewAmex = new tblAuthForm()
                                    {
                                        VendorID = Row.VendorID,
                                        GroupID = Row.GroupID,
                                        CardID = CardIDToSave,
                                        PaymentDate = Row.ThirdPayDate,
                                        AuthAmt = Row.ThirdPayAmt,
                                        LineNo = 3,
                                        ArrivalDate = StartDate,
                                        Category = null,
                                    };
                                    _context.tblAuthForms.Add(NewAmex);
                                }
                            }
                        }
                    }
                    foreach (var Mconf in ChangedMiscConf)
                    {
                        var Row = Data.SaveRows.Where(row => row.VendorID == Mconf.VendorID && row.GroupID == Mconf.GroupID && row.StartDate == Mconf.StartDate).FirstOrDefault();
                        if (Row != null && (Row.NewVendorID == null || Row.NewVendorID == Row.VendorID))
                        {
                            Mconf.Pax = Row.Pax;
                            Mconf.EmployeeID = Row.EmployeeID;
                            Mconf.ServiceDetID = Row.ServiceID;
                            Mconf.Time = Row.Time;
                            Mconf.StatusID = Row.SelectedVendorStatus;
                            Mconf.Notes = Row.Notes;
                            Mconf.UnitPrice = Row.UnitPrice;
                            Mconf.UnitPricePerGroup = Row.UnitPricePG;
                            Mconf.IsComp = Row.IsComp;
                            Mconf.FirstPayment = Row.FirstPayAmt;
                            Mconf.FirstPaymentMethod = Row.FirstPayMethod;
                            Mconf.FirstPaymentDate = Row.FirstPayDate;
                            Mconf.SecondPayment = Row.SecondPayAmt;
                            Mconf.SecondPaymentMethod = Row.SecondPayMethod;
                            Mconf.SecondPaymentDate = Row.SecondPayDate;
                            Mconf.ThirdPayment = Row.ThirdPayAmt;
                            Mconf.ThirdPaymentMethod = Row.ThirdPayMethod;
                            Mconf.ThirdPaymentDate = Row.ThirdPayDate;
                            if (Row.NewStartDate != null && Row.NewStartDate != Row.StartDate)
                            {
                                tblMiscConfirm NewMisc = new tblMiscConfirm()
                                {
                                    GroupID = Mconf.GroupID,
                                    VendorID = Row.VendorID,
                                    StartDate = (DateTime)Row.NewStartDate,
                                    QuotaRate = Mconf.QuotaRate,
                                    QuotaCurr = Mconf.QuotaCurr,
                                    QuotaVendorID = Mconf.QuotaVendorID,
                                    QuotaVendorDesc = Mconf.QuotaVendorDesc,
                                    ServiceDetID = Row.ServiceID,
                                    Time = Row.Time,
                                    StatusID = Row.SelectedVendorStatus,
                                    EmployeeID = Row.EmployeeID,
                                    Notes = Row.Notes,
                                    MiscConfirmFile = Mconf.MiscConfirmFile,
                                    PlaneFlag = Mconf.PlaneFlag,
                                    IsComp = Row.IsComp,
                                    UnitPrice = Row.UnitPrice,
                                    UnitPricePerGroup = Row.UnitPricePG,
                                    Pax = Row.Pax,
                                    FirstPayment = Row.FirstPayAmt,
                                    FirstPaymentMethod = Row.FirstPayMethod,
                                    FirstPaymentDate = Row.FirstPayDate,
                                    SecondPayment = Row.SecondPayAmt,
                                    SecondPaymentMethod = Row.SecondPayMethod,
                                    SecondPaymentDate = Row.SecondPayDate,
                                    ThirdPayment = Row.ThirdPayAmt,
                                    ThirdPaymentMethod = Row.ThirdPayMethod,
                                    ThirdPaymentDate = Row.ThirdPayDate,
                                };
                                _context.tblMiscConfirms.Remove(Mconf);
                                _context.tblMiscConfirms.Add(NewMisc);
                            }
                        }
                    }
                    if (Data.SaveRows.Any(row => row.NewVendorID != null && row.VendorID == 0 && row.NewStartDate != null && row.StartDate == null))
                    {
                        var SaveRows = Data.SaveRows.Where(row => row.NewVendorID != null && row.VendorID == 0 && row.NewStartDate != null && row.StartDate == null).ToList();
                        // New Misc Confirm
                        foreach (var row in SaveRows)
                        {
                            tblMiscConfirm newMisc = new tblMiscConfirm()
                            {
                                GroupID = row.GroupID,
                                VendorID = (int)row.NewVendorID,
                                StartDate = (DateTime)row.NewStartDate,
                                Time = row.Time,
                                StatusID = row.SelectedVendorStatus,
                                EmployeeID = row.EmployeeID,
                                Notes = row.Notes,
                                ServiceDetID = row.ServiceID,
                                QuotaCurr = row.QuotaCurr,
                                QuotaRate = row.QuotaRate,
                                PlaneFlag = row.Plane,
                                IsComp = row.IsComp,
                                UnitPrice = row.UnitPrice,
                                UnitPricePerGroup = row.UnitPricePG,
                                Pax = row.Pax,
                                FirstPayment = row.FirstPayAmt,
                                FirstPaymentMethod = row.FirstPayMethod,
                                FirstPaymentDate = row.FirstPayDate,
                                SecondPayment = row.SecondPayAmt,
                                SecondPaymentMethod = row.SecondPayMethod,
                                SecondPaymentDate = row.SecondPayDate,
                                ThirdPayment = row.ThirdPayAmt,
                                ThirdPaymentMethod = row.ThirdPayMethod,
                                ThirdPaymentDate = row.ThirdPayDate,
                            };
                            _context.tblMiscConfirms.Add(newMisc);
                        }
                    }
                    _context.SaveChanges();
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    Error.errorCode = 5643;
                    Error.Message = ex.Message;
                    logger.Error(ex.ToMessageAndCompleteStacktrace());
                    transaction.Rollback();
                }
            }
            return OperationSearchMisc(Data, FilterData, PageNum, UserRegions, UserName);
        }
        public OperationBusGridBData SaveOperationBus(OperationBusGridBData Data, OperationBusFilterBData FilterData, int PageNum, List<string> UserRegions, string UserName)
        {
            ErrorBInfo Error = new ErrorBInfo();
            using (var transaction = _context.Database.BeginTransaction(IsolationLevel.Serializable))
            {
                try
                {
                    List<tblBusConfirm> RemoveList = new List<tblBusConfirm>();
                    List<tblBusConfirm> AddList = new List<tblBusConfirm>();
                    var CardTypes = _context.tblCardTypes.Select(cardtype => cardtype).ToList();
                    var VendorIds = Data.SaveRows.Select(row => row.VendorID).ToList();
                    var GuideIds = Data.SaveRows.Select(row => row.SelectedGuideID).ToList();
                    var NewVendorIds = Data.SaveRows.Select(row => row.NewVendorID).ToList();
                    var Vendors = _context.tblVendors.Where(Vnd => VendorIds.Contains(Vnd.VendorID) || NewVendorIds.Contains(Vnd.VendorID)).ToList();
                    var GroupIds = Data.SaveRows.GroupBy(row => row.GroupID).Select(row => row.Key).ToList();
                    var Groups = _context.tblGroups.Where(grp => GroupIds.Contains(grp.GroupID)).ToList();
                    foreach (var grp in Groups)
                        grp.TechProgUpdt = true;
                    var StartDates = Data.SaveRows.Select(row => row.StartDate).ToList();
                    var ChangedBusConf = _context.tblBusConfirms.Where(busC => VendorIds.Contains(busC.VendorID) && GroupIds.Contains(busC.GroupID)).ToList();
                    var ChangedGuideConf = _context.tblGuideConfirms.Where(guideC => GuideIds.Contains(guideC.GuideID) && GroupIds.Contains(guideC.GroupID)).ToList();
                    var ChangedAmexVendor = _context.tblAuthForms.Where(amex => VendorIds.Contains((int)amex.VendorID) && GroupIds.Contains((int)amex.GroupID) && StartDates.Contains(amex.ArrivalDate)).ToList();
                    var ChangedAmexGuide = _context.tblAuthForms.Where(amex => GuideIds.Contains((int)amex.VendorID) && GroupIds.Contains((int)amex.GroupID) && StartDates.Contains(amex.ArrivalDate)).ToList();
                    var ChangedGirGrpInvoices = _context.tblGirGroupInvoices.Where(Inv => GroupIds.Contains(Inv.GroupID) && VendorIds.Contains((int)Inv.VendorID)).ToList();
                    var ChangedGrpInvoices = _context.tblGroupInvoices.Where(Inv => GroupIds.Contains(Inv.GroupID)).ToList();
                    Dictionary<int, int> LineNoNonGir = new Dictionary<int, int>();
                    foreach (var GrId in GroupIds)
                        LineNoNonGir.Add(GrId, 0);
                    foreach (var Row in Data.SaveRows)
                    {
                        var CurrGrp = Groups.Where(grp => grp.GroupID == Row.GroupID).SingleOrDefault();
                        if (CurrGrp != null && CurrGrp.IsGir == true)
                        {
                            // Gir Group Invoice
                            var ChangeGirInv = ChangedGirGrpInvoices.Where(Inv => Inv.GroupID == Row.GroupID && Inv.VendorID == Row.VendorID).ToList();

                        }
                        else
                        {
                            // ad hock Group Invoice
                            var ChangeInv = ChangedGrpInvoices.Any(Inv => Inv.GroupID == Row.GroupID && Inv.VendorID == Row.VendorID) ? ChangedGrpInvoices.Where(Inv => Inv.GroupID == Row.GroupID && Inv.VendorID == Row.VendorID).FirstOrDefault() : null;
                            if (LineNoNonGir[Row.GroupID] == 0)
                                LineNoNonGir[Row.GroupID] = ChangedGrpInvoices.Any(Inv => Inv.GroupID == Row.GroupID) ? ChangedGrpInvoices.Max(Inv => Inv.LineNo) + 1 : 1;
                            if (ChangeInv == null && Row.IsInvoice == true)
                            {
                                // new Invoice
                                int? CurrVId = Row.NewVendorID != null ? Row.NewVendorID : Row.VendorID;
                                //var PriceChange = CurrGrp.UsdCadRate != null ? (decimal)CurrGrp.UsdCadRate * (decimal)Row.InvoicePrice : (decimal)Row.InvoicePrice;
                                var GroupInv = new tblGroupInvoice
                                {
                                    GroupID = Row.GroupID,
                                    VendorID = CurrVId,
                                    Price = (decimal)Row.InvoicePrice,
                                    PriceChange = (decimal)Row.InvoicePrice,
                                    Currency = Row.QuotaCurr,
                                    ItemTypeID = 0,
                                    DebCre = false,
                                    Quantity = (int)Row.BusCount,
                                    Debit = (int)Row.BusCount * (decimal)Row.InvoicePrice,
                                    LineNo = LineNoNonGir[Row.GroupID],
                                    Description = Vendors.Where(Vnd => Vnd.VendorID == CurrVId).Select(Vnd => Vnd.VendorName).SingleOrDefault(),
                                };
                                _context.tblGroupInvoices.Add(GroupInv);
                                LineNoNonGir[Row.GroupID] = LineNoNonGir[Row.GroupID] + 1;
                            }
                            else if (ChangeInv != null && Row.IsInvoice == true)
                            {
                                ChangeInv.Price = (decimal)Row.InvoicePrice;
                                ChangeInv.PriceChange = (decimal)Row.InvoicePrice;
                                ChangeInv.Quantity = (int)Row.BusCount;
                                if (ChangeInv.DebCre == true)
                                    ChangeInv.Credit = (int)Row.BusCount * (decimal)Row.InvoicePrice;
                                else
                                    ChangeInv.Debit = (int)Row.BusCount * (decimal)Row.InvoicePrice;
                            }
                            else if(ChangeInv != null && Row.IsInvoice == false)
                            {
                                ChangeInv.Price = 0;
                                ChangeInv.PriceChange = 0;
                                ChangeInv.Quantity = 0;
                                if (ChangeInv.DebCre == true)
                                    ChangeInv.Credit = 0;
                                else
                                    ChangeInv.Debit = 0;
                            }

                        }
                        if (Row.GroupID != 0)
                        {
                            if (Row.NewVendorID == null || Row.NewVendorID == Row.VendorID)
                            {
                                var StartDate = Row.StartDate;
                                if (Row.NewStartDate != null && Row.NewStartDate != Row.StartDate)
                                    StartDate = (DateTime)Row.NewStartDate;
                                var Time = Row.Time;
                                if (Row.NewTime != null && (Convert.ToDateTime(Row.NewTime).Hour != Convert.ToDateTime(Row.Time).Hour || Convert.ToDateTime(Row.NewTime).Minute != Convert.ToDateTime(Row.Time).Minute))
                                    Time = Row.NewTime;
                                if ((Row.SelectedGuideID != null && Row.SelectedGuideID != 0) || (Row.NewSelectedGuideID != null && Row.NewSelectedGuideID != 0))
                                {
                                    var GuideID = Row.SelectedGuideID;
                                    if (Row.NewSelectedGuideID != null && Row.NewSelectedGuideID != Row.SelectedGuideID)
                                        GuideID = (int)Row.NewSelectedGuideID;
                                    var amexEditGuide = ChangedAmexGuide.Where(amex => Row.SelectedGuideID == amex.VendorID && Row.GroupID == amex.GroupID && Row.StartDate == amex.ArrivalDate && "Guide" == amex.Category).ToList();
                                    if (amexEditGuide.Any(amex => amex.LineNo == 1))
                                    {
                                        var amexEditFirstList = amexEditGuide.Where(amex => amex.LineNo == 1).ToList();
                                        var amexEditFirst = amexEditFirstList.FirstOrDefault();
                                        if (Row.Time != null)
                                            foreach (var amexrow in amexEditFirstList)
                                            {
                                                if (Convert.ToDateTime(Row.Time).Hour == Convert.ToDateTime(amexrow.Time).Hour && Convert.ToDateTime(Row.Time).Minute == Convert.ToDateTime(amexrow.Time).Minute)
                                                    amexEditFirst = amexrow;
                                                break;

                                            }
                                        else
                                            amexEditFirst = amexEditFirstList.Where(amex => amex.Time == null).FirstOrDefault();
                                        amexEditFirst.AuthAmt = Row.GuideFirstPayAmt;
                                        amexEditFirst.PaymentDate = Row.GuideFirstPayDate;
                                        amexEditFirst.CardID = CardTypes.Where(card => card.CardTypeCode == Row.GuideFirstPayMethod).Select(card => card.CardTypeID).SingleOrDefault();
                                        amexEditFirst.Category = "Guide";
                                        amexEditFirst.VendorID = GuideID;
                                        amexEditFirst.Time = Time;
                                        amexEditFirst.ArrivalDate = StartDate;
                                    }
                                    else
                                    {
                                        var CardIDToSave = CardTypes.Where(card => card.CardTypeCode == Row.GuideFirstPayMethod).Select(card => card.CardTypeID).SingleOrDefault();
                                        tblAuthForm NewAmex = new tblAuthForm()
                                        {
                                            VendorID = GuideID,
                                            GroupID = Row.GroupID,
                                            CardID = CardIDToSave,
                                            PaymentDate = Row.GuideFirstPayDate,
                                            AuthAmt = Row.GuideFirstPayAmt,
                                            LineNo = 1,
                                            ArrivalDate = StartDate,
                                            Category = "Guide",
                                            Time = Time,
                                        };
                                        _context.tblAuthForms.Add(NewAmex);
                                    }
                                    if (amexEditGuide.Any(amex => amex.LineNo == 2))
                                    {
                                        var amexEditSecondList = amexEditGuide.Where(amex => amex.LineNo == 2).ToList();
                                        var amexEditSecond = amexEditSecondList.FirstOrDefault();
                                        if (Row.Time != null)
                                            foreach (var amexrow in amexEditSecondList)
                                            {
                                                if (Convert.ToDateTime(Row.Time).Hour == Convert.ToDateTime(amexrow.Time).Hour && Convert.ToDateTime(Row.Time).Minute == Convert.ToDateTime(amexrow.Time).Minute)
                                                    amexEditSecond = amexrow;
                                                break;

                                            }
                                        else
                                            amexEditSecond = amexEditSecondList.Where(amex => amex.Time == null).FirstOrDefault();
                                        amexEditSecond.AuthAmt = Row.GuideSecondPayAmt;
                                        amexEditSecond.PaymentDate = Row.GuideSecondPayDate;
                                        amexEditSecond.CardID = CardTypes.Where(card => card.CardTypeCode == Row.GuideSecondPayMethod).Select(card => card.CardTypeID).SingleOrDefault();
                                        amexEditSecond.Category = "Guide";
                                        amexEditSecond.VendorID = GuideID;
                                        amexEditSecond.Time = Time;
                                        amexEditSecond.ArrivalDate = StartDate;
                                    }
                                    else
                                    {
                                        var CardIDToSave = CardTypes.Where(card => card.CardTypeCode == Row.GuideSecondPayMethod).Select(card => card.CardTypeID).SingleOrDefault();
                                        tblAuthForm NewAmex = new tblAuthForm()
                                        {
                                            VendorID = GuideID,
                                            GroupID = Row.GroupID,
                                            CardID = CardIDToSave,
                                            PaymentDate = Row.GuideSecondPayDate,
                                            AuthAmt = Row.GuideSecondPayAmt,
                                            LineNo = 2,
                                            ArrivalDate = StartDate,
                                            Category = "Guide",
                                            Time = Time
                                        };
                                        _context.tblAuthForms.Add(NewAmex);
                                    }
                                    if (amexEditGuide.Any(amex => amex.LineNo == 3))
                                    {
                                        var amexEditThirdList = amexEditGuide.Where(amex => amex.LineNo == 3).ToList();
                                        var amexEditThird = amexEditThirdList.FirstOrDefault();
                                        if (Row.Time != null)
                                            foreach (var amexrow in amexEditThirdList)
                                            {
                                                if (Convert.ToDateTime(Row.Time).Hour == Convert.ToDateTime(amexrow.Time).Hour && Convert.ToDateTime(Row.Time).Minute == Convert.ToDateTime(amexrow.Time).Minute)
                                                    amexEditThird = amexrow;
                                                break;

                                            }
                                        else
                                            amexEditThird = amexEditThirdList.Where(amex => amex.Time == null).FirstOrDefault();
                                        amexEditThird.AuthAmt = Row.GuideThirdPayAmt;
                                        amexEditThird.PaymentDate = Row.GuideThirdPayDate;
                                        amexEditThird.CardID = CardTypes.Where(card => card.CardTypeCode == Row.GuideThirdPayMethod).Select(card => card.CardTypeID).SingleOrDefault();
                                        amexEditThird.Category = "Guide";
                                        amexEditThird.VendorID = GuideID;
                                        amexEditThird.Time = Time;
                                        amexEditThird.ArrivalDate = StartDate;
                                    }
                                    else
                                    {
                                        var CardIDToSave = CardTypes.Where(card => card.CardTypeCode == Row.GuideThirdPayMethod).Select(card => card.CardTypeID).SingleOrDefault();
                                        tblAuthForm NewAmex = new tblAuthForm()
                                        {
                                            VendorID = GuideID,
                                            GroupID = Row.GroupID,
                                            CardID = CardIDToSave,
                                            PaymentDate = Row.GuideThirdPayDate,
                                            AuthAmt = Row.GuideThirdPayAmt,
                                            LineNo = 3,
                                            ArrivalDate = StartDate,
                                            Category = "Guide",
                                            Time = Time,
                                        };
                                        _context.tblAuthForms.Add(NewAmex);
                                    }
                                }
                                var amexEdit = ChangedAmexVendor.Where(amex => Row.VendorID == amex.VendorID && Row.GroupID == amex.GroupID && Row.StartDate == amex.ArrivalDate && null == amex.Category).ToList();
                                if (amexEdit.Any(amex => amex.LineNo == 1))
                                {
                                    var amexEditFirstList = amexEdit.Where(amex => amex.LineNo == 1).ToList();
                                    var amexEditFirst = amexEditFirstList.FirstOrDefault();
                                    if (Row.Time != null)
                                        foreach (var amexrow in amexEditFirstList)
                                        {
                                            if (Convert.ToDateTime(Row.Time).Hour == Convert.ToDateTime(amexrow.Time).Hour && Convert.ToDateTime(Row.Time).Minute == Convert.ToDateTime(amexrow.Time).Minute)
                                                amexEditFirst = amexrow;
                                            break;

                                        }
                                    else
                                        amexEditFirst = amexEditFirstList.Where(amex => amex.Time == null).FirstOrDefault();
                                    amexEditFirst.AuthAmt = Row.FirstPayAmt;
                                    amexEditFirst.PaymentDate = Row.FirstPayDate;
                                    amexEditFirst.CardID = CardTypes.Where(card => card.CardTypeCode == Row.FirstPayMethod).Select(card => card.CardTypeID).SingleOrDefault();
                                    amexEditFirst.Category = null;
                                    amexEditFirst.ArrivalDate = StartDate;
                                    amexEditFirst.Time = Time;
                                }
                                else
                                {
                                    var CardIDToSave = CardTypes.Where(card => card.CardTypeCode == Row.FirstPayMethod).Select(card => card.CardTypeID).SingleOrDefault();
                                    tblAuthForm NewAmex = new tblAuthForm()
                                    {
                                        VendorID = Row.VendorID,
                                        GroupID = Row.GroupID,
                                        CardID = CardIDToSave,
                                        PaymentDate = Row.FirstPayDate,
                                        AuthAmt = Row.FirstPayAmt,
                                        LineNo = 1,
                                        ArrivalDate = StartDate,
                                        Category = null,
                                        Time = Time,
                                    };
                                    _context.tblAuthForms.Add(NewAmex);
                                }
                                if (amexEdit.Any(amex => amex.LineNo == 2))
                                {
                                    var amexEditSecondList = amexEdit.Where(amex => amex.LineNo == 2).ToList();
                                    var amexEditSecond = amexEditSecondList.FirstOrDefault();
                                    if (Row.Time != null)
                                        foreach (var amexrow in amexEditSecondList)
                                        {
                                            if (Convert.ToDateTime(Row.Time).Hour == Convert.ToDateTime(amexrow.Time).Hour && Convert.ToDateTime(Row.Time).Minute == Convert.ToDateTime(amexrow.Time).Minute)
                                                amexEditSecond = amexrow;
                                            break;

                                        }
                                    else
                                        amexEditSecond = amexEditSecondList.Where(amex => amex.Time == null).FirstOrDefault();
                                    amexEditSecond.AuthAmt = Row.SecondPayAmt;
                                    amexEditSecond.PaymentDate = Row.SecondPayDate;
                                    amexEditSecond.CardID = CardTypes.Where(card => card.CardTypeCode == Row.SecondPayMethod).Select(card => card.CardTypeID).SingleOrDefault();
                                    amexEditSecond.Category = null;
                                    amexEditSecond.ArrivalDate = StartDate;
                                    amexEditSecond.Time = Time;
                                }
                                else
                                {
                                    var CardIDToSave = CardTypes.Where(card => card.CardTypeCode == Row.SecondPayMethod).Select(card => card.CardTypeID).SingleOrDefault();
                                    tblAuthForm NewAmex = new tblAuthForm()
                                    {
                                        VendorID = Row.VendorID,
                                        GroupID = Row.GroupID,
                                        CardID = CardIDToSave,
                                        PaymentDate = Row.SecondPayDate,
                                        AuthAmt = Row.SecondPayAmt,
                                        LineNo = 2,
                                        ArrivalDate = StartDate,
                                        Category = null,
                                        Time = Time,
                                    };
                                    _context.tblAuthForms.Add(NewAmex);
                                }
                                if (amexEdit.Any(amex => amex.LineNo == 3))
                                {
                                    var amexEditThirdList = amexEdit.Where(amex => amex.LineNo == 3).ToList();
                                    var amexEditThird = amexEditThirdList.FirstOrDefault();
                                    if (Row.Time != null)
                                        foreach (var amexrow in amexEditThirdList)
                                        {
                                            if (Convert.ToDateTime(Row.Time).Hour == Convert.ToDateTime(amexrow.Time).Hour && Convert.ToDateTime(Row.Time).Minute == Convert.ToDateTime(amexrow.Time).Minute)
                                                amexEditThird = amexrow;
                                            break;

                                        }
                                    else
                                        amexEditThird = amexEditThirdList.Where(amex => amex.Time == null).FirstOrDefault();
                                    amexEditThird.AuthAmt = Row.ThirdPayAmt;
                                    amexEditThird.PaymentDate = Row.ThirdPayDate;
                                    amexEditThird.CardID = CardTypes.Where(card => card.CardTypeCode == Row.ThirdPayMethod).Select(card => card.CardTypeID).SingleOrDefault();
                                    amexEditThird.Category = null;
                                    amexEditThird.ArrivalDate = StartDate;
                                    amexEditThird.Time = Time;
                                }
                                else
                                {
                                    var CardIDToSave = CardTypes.Where(card => card.CardTypeCode == Row.ThirdPayMethod).Select(card => card.CardTypeID).SingleOrDefault();
                                    tblAuthForm NewAmex = new tblAuthForm()
                                    {
                                        VendorID = Row.VendorID,
                                        GroupID = Row.GroupID,
                                        CardID = CardIDToSave,
                                        PaymentDate = Row.ThirdPayDate,
                                        AuthAmt = Row.ThirdPayAmt,
                                        LineNo = 3,
                                        ArrivalDate = StartDate,
                                        Category = null,
                                        Time = Time,
                                    };
                                    _context.tblAuthForms.Add(NewAmex);
                                }
                            }
                        }
                    }
                    foreach (var Bconf in ChangedBusConf)
                    {
                        var Row = Data.SaveRows.Where(row => row.VendorID == Bconf.VendorID && row.GroupID == Bconf.GroupID && row.StartDate == Bconf.StartDate).FirstOrDefault();
                        // Vendor changed such find bus to normal bus
                        if (Row != null && Row.NewVendorID != null && Row.NewVendorID != Row.VendorID)
                        {
                            var Time = Row.Time;
                            if (Row.NewTime != null && (Convert.ToDateTime(Row.NewTime).Hour != Convert.ToDateTime(Row.Time).Hour || Convert.ToDateTime(Row.NewTime).Minute != Convert.ToDateTime(Row.Time).Minute))
                                Time = Row.NewTime;
                            if (Row.IsInvoice == true)
                                Bconf.Pax = Row.Pax;
                            tblBusConfirm NewBus = new tblBusConfirm()
                            {
                                GroupID = Bconf.GroupID,
                                VendorID = (int)Row.NewVendorID,
                                StartDate = Bconf.StartDate,
                                Time = Time,
                                QuotaRate = Bconf.QuotaRate,
                                QuotaCurr = Bconf.QuotaCurr,
                                FinishDate = Bconf.FinishDate,
                                ConfirmDate = Bconf.ConfirmDate,
                                ServiceDetID = Row.ServiceDetailID,
                                ServiceID = Row.ServiceID,
                                EmployeeID = Row.EmployeeID,
                                Airport = Row.Airport,
                                BusCount = Row.BusCount,
                                BusPrice = Row.BusPrice,
                                BusSize = Row.BusSize,
                                EndCity = Row.EndCity,
                                QuotaVendorID = Bconf.QuotaVendorID,
                                QuotaVendorDesc = Bconf.QuotaVendorDesc,
                                IsInvoice = Row.IsInvoice,
                                InvoicePrice = Row.InvoicePrice,
                                Pax = Row.IsInvoice == true ? Row.Pax : Bconf.Pax,
                                StatusID = Row.SelectedVendorStatus,
                                FirstPayment = Row.FirstPayAmt,
                                FirstPaymentMethod = Row.FirstPayMethod,
                                FirstPaymentDate = Row.FirstPayDate,
                                SecondPayment = Row.SecondPayAmt,
                                SecondPaymentMethod = Row.SecondPayMethod,
                                SecondPaymentDate = Row.SecondPayDate,
                                ThirdPayment = Row.ThirdPayAmt,
                                ThirdPaymentMethod = Row.ThirdPayMethod,
                                ThirdPaymentDate = Row.ThirdPayDate,
                                Notes = Row.Notes,
                                BusConfirmFile = Bconf.BusConfirmFile,
                            };
                            _context.tblBusConfirms.Remove(Bconf);
                            _context.tblBusConfirms.Add(NewBus);
                        }
                        if (Row != null && (Row.NewVendorID == null || Row.NewVendorID == Row.VendorID))
                        {
                            var Time = Row.Time;
                            if (Row.NewTime != null && (Convert.ToDateTime(Row.NewTime).Hour != Convert.ToDateTime(Row.Time).Hour || Convert.ToDateTime(Row.NewTime).Minute != Convert.ToDateTime(Row.Time).Minute))
                                Time = Row.NewTime;
                            if (Row.IsInvoice == true)
                                Bconf.Pax = Row.Pax;
                            Bconf.Time = Time;
                            Bconf.ServiceDetID = Row.ServiceDetailID;
                            Bconf.ServiceID = Row.ServiceID;
                            Bconf.EmployeeID = Row.EmployeeID;
                            Bconf.StatusID = Row.SelectedVendorStatus;
                            Bconf.ServiceDate = Row.ServiceDate;
                            Bconf.BusSize = Row.BusSize;
                            Bconf.BusCount = Row.BusCount;
                            Bconf.BusPrice = Row.BusPrice;
                            Bconf.Airport = Row.Airport;
                            Bconf.StartCity = Row.StartCity;
                            Bconf.EndCity = Row.EndCity;
                            Bconf.IsInvoice = Row.IsInvoice;
                            Bconf.InvoicePrice = Row.InvoicePrice;
                            Bconf.FirstPayment = Row.FirstPayAmt;
                            Bconf.FirstPaymentMethod = Row.FirstPayMethod;
                            Bconf.FirstPaymentDate = Row.FirstPayDate;
                            Bconf.SecondPayment = Row.SecondPayAmt;
                            Bconf.SecondPaymentMethod = Row.SecondPayMethod;
                            Bconf.SecondPaymentDate = Row.SecondPayDate;
                            Bconf.ThirdPayment = Row.ThirdPayAmt;
                            Bconf.ThirdPaymentMethod = Row.ThirdPayMethod;
                            Bconf.ThirdPaymentDate = Row.ThirdPayDate;
                            Bconf.Notes = Row.Notes;
                            if (Row != null && Row.NewStartDate != null && Row.NewStartDate != Row.StartDate)
                            {
                                tblBusConfirm NewBus = new tblBusConfirm()
                                {
                                    GroupID = Bconf.GroupID,
                                    VendorID = Row.VendorID,
                                    StartDate = (DateTime)Row.NewStartDate,
                                    Time = Time,
                                    QuotaRate = Bconf.QuotaRate,
                                    QuotaCurr = Bconf.QuotaCurr,
                                    FinishDate = Bconf.FinishDate,
                                    ConfirmDate = Bconf.ConfirmDate,
                                    ServiceDetID = Row.ServiceDetailID,
                                    ServiceID = Row.ServiceID,
                                    EmployeeID = Row.EmployeeID,
                                    Airport = Row.Airport,
                                    BusCount = Row.BusCount,
                                    BusPrice = Row.BusPrice,
                                    BusSize = Row.BusSize,
                                    EndCity = Row.EndCity,
                                    QuotaVendorID = Bconf.QuotaVendorID,
                                    QuotaVendorDesc = Bconf.QuotaVendorDesc,
                                    IsInvoice = Row.IsInvoice,
                                    InvoicePrice = Row.InvoicePrice,
                                    Pax = Row.IsInvoice == true ? Row.Pax : Bconf.Pax,
                                    StatusID = Row.SelectedVendorStatus,
                                    FirstPayment = Row.FirstPayAmt,
                                    FirstPaymentMethod = Row.FirstPayMethod,
                                    FirstPaymentDate = Row.FirstPayDate,
                                    SecondPayment = Row.SecondPayAmt,
                                    SecondPaymentMethod = Row.SecondPayMethod,
                                    SecondPaymentDate = Row.SecondPayDate,
                                    ThirdPayment = Row.ThirdPayAmt,
                                    ThirdPaymentMethod = Row.ThirdPayMethod,
                                    ThirdPaymentDate = Row.ThirdPayDate,
                                    Notes = Row.Notes,
                                    BusConfirmFile = Bconf.BusConfirmFile,
                                };
                                _context.tblBusConfirms.Remove(Bconf);
                                _context.tblBusConfirms.Add(NewBus);
                            }
                        }
                    }
                    foreach (var Gconf in ChangedGuideConf)
                    {
                        var Row = Data.SaveRows.Where(row => row.SelectedGuideID == Gconf.GuideID && row.GroupID == Gconf.GroupID && row.StartDate == Gconf.StartDate).FirstOrDefault();
                        // Change Vendor such find guide to normal guide
                        if (Row != null && Row.NewSelectedGuideID != null && Row.NewSelectedGuideID != Row.SelectedGuideID)
                        {
                            var Time = Row.Time;
                            if (Row.NewTime != null && (Convert.ToDateTime(Row.NewTime).Hour != Convert.ToDateTime(Row.Time).Hour || Convert.ToDateTime(Row.NewTime).Minute != Convert.ToDateTime(Row.Time).Minute))
                                Time = Row.NewTime;
                            tblGuideConfirm NewGuide = new tblGuideConfirm()
                            {
                                GroupID = Gconf.GroupID,
                                GuideID = (int)Row.NewSelectedGuideID,
                                Selected = Gconf.Selected,
                                ConfirmDate = Gconf.ConfirmDate,
                                StartDate = Gconf.StartDate,
                                Time = Time,
                                FinishDate = Gconf.FinishDate,
                                RoadTrip = Gconf.RoadTrip,
                                LocalWork = Gconf.LocalWork,
                                Notes = Gconf.Notes,
                                GInvoice = Gconf.GInvoice,
                                QuotaRate = Gconf.QuotaRate,
                                QuotaCurr = Gconf.QuotaCurr,
                                QuotaGuideID = Gconf.QuotaGuideID,
                                QuotaGuideDesc = Gconf.QuotaGuideDesc,
                                EmployeeID = Row.EmployeeID,
                                Salary = Row.GuideSalary,
                                GuideMisc = Row.GuideMisc,
                                GuideStepOn = Row.GuideStepOn,
                                SalaryPaid = Row.GuideSalaryPaid,
                                PaidAmt = Row.GuidePaidAmt,
                                AddCharge = Row.GuideAddCharge,
                                FirstPayment = Row.FirstPayAmt,
                                FirstPaymentMethod = Row.FirstPayMethod,
                                FirstPaymentDate = Row.FirstPayDate,
                                SecondPayment = Row.SecondPayAmt,
                                SecondPaymentMethod = Row.SecondPayMethod,
                                SecondPaymentDate = Row.SecondPayDate,
                                ThirdPayment = Row.ThirdPayAmt,
                                ThirdPaymentMethod = Row.ThirdPayMethod,
                                ThirdPaymentDate = Row.ThirdPayDate,
                            };
                            _context.tblGuideConfirms.Remove(Gconf);
                            _context.tblGuideConfirms.Add(NewGuide);
                        }
                        if (Row != null && (Row.NewVendorID == null || Row.NewVendorID == Row.VendorID))
                        {
                            var Time = Row.Time;
                            if (Row.NewTime != null && (Convert.ToDateTime(Row.NewTime).Hour != Convert.ToDateTime(Row.Time).Hour || Convert.ToDateTime(Row.NewTime).Minute != Convert.ToDateTime(Row.Time).Minute))
                                Time = Row.NewTime;

                            Gconf.Time = Time;
                            Gconf.EmployeeID = Row.EmployeeID;
                            Gconf.FirstPayment = Row.GuideFirstPayAmt;
                            Gconf.FirstPaymentMethod = Row.GuideFirstPayMethod;
                            Gconf.FirstPaymentDate = Row.GuideFirstPayDate;
                            Gconf.SecondPayment = Row.GuideSecondPayAmt;
                            Gconf.SecondPaymentMethod = Row.GuideSecondPayMethod;
                            Gconf.SecondPaymentDate = Row.GuideSecondPayDate;
                            Gconf.ThirdPayment = Row.GuideThirdPayAmt;
                            Gconf.ThirdPaymentMethod = Row.GuideThirdPayMethod;
                            Gconf.ThirdPaymentDate = Row.GuideThirdPayDate;
                            Gconf.Salary = Row.GuideSalary;
                            Gconf.GuideMisc = Row.GuideMisc;
                            Gconf.GuideStepOn = Row.GuideStepOn;
                            Gconf.SalaryPaid = Row.GuideSalaryPaid;
                            Gconf.PaidAmt = Row.GuidePaidAmt;
                            Gconf.AddCharge = Row.GuideAddCharge;
                            if (Row != null && (Row.NewSelectedGuideID != null && Row.NewSelectedGuideID != Row.SelectedGuideID) || (Row.NewStartDate != null && Row.NewStartDate != Row.StartDate))
                            {
                                var StartDate = (DateTime)Row.StartDate;
                                if (Row.NewStartDate != null && Row.NewStartDate != Row.StartDate)
                                    StartDate = (DateTime)Row.NewStartDate;
                                var SelectedGuideID = (int)Row.SelectedGuideID;
                                if (Row.NewSelectedGuideID != null && Row.NewSelectedGuideID != Row.SelectedGuideID)
                                    SelectedGuideID = (int)Row.NewSelectedGuideID;
                                tblGuideConfirm NewGuide = new tblGuideConfirm()
                                {
                                    GroupID = Gconf.GroupID,
                                    GuideID = SelectedGuideID,
                                    Selected = Gconf.Selected,
                                    ConfirmDate = Gconf.ConfirmDate,
                                    StartDate = StartDate,
                                    Time = Time,
                                    FinishDate = Gconf.FinishDate,
                                    RoadTrip = Gconf.RoadTrip,
                                    LocalWork = Gconf.LocalWork,
                                    Notes = Gconf.Notes,
                                    GInvoice = Gconf.GInvoice,
                                    QuotaRate = Gconf.QuotaRate,
                                    QuotaCurr = Gconf.QuotaCurr,
                                    QuotaGuideID = Gconf.QuotaGuideID,
                                    QuotaGuideDesc = Gconf.QuotaGuideDesc,
                                    EmployeeID = Row.EmployeeID,
                                    Salary = Row.GuideSalary,
                                    GuideMisc = Row.GuideMisc,
                                    GuideStepOn = Row.GuideStepOn,
                                    SalaryPaid = Row.GuideSalaryPaid,
                                    PaidAmt = Row.GuidePaidAmt,
                                    AddCharge = Row.GuideAddCharge,
                                    FirstPayment = Row.FirstPayAmt,
                                    FirstPaymentMethod = Row.FirstPayMethod,
                                    FirstPaymentDate = Row.FirstPayDate,
                                    SecondPayment = Row.SecondPayAmt,
                                    SecondPaymentMethod = Row.SecondPayMethod,
                                    SecondPaymentDate = Row.SecondPayDate,
                                    ThirdPayment = Row.ThirdPayAmt,
                                    ThirdPaymentMethod = Row.ThirdPayMethod,
                                    ThirdPaymentDate = Row.ThirdPayDate,
                                };
                                _context.tblGuideConfirms.Remove(Gconf);
                                _context.tblGuideConfirms.Add(NewGuide);
                            }
                        }
                    }
                    if (Data.SaveRows.Any(row => row.NewSelectedGuideID != null && row.SelectedGuideID == 0 && (row.NewStartDate != null || row.StartDate == null)))
                    {
                        var SaveRows = Data.SaveRows.Where(row => row.NewSelectedGuideID != null && row.SelectedGuideID == 0).ToList();
                        // New Attraction or Restaurant Confirm
                        foreach (var Row in SaveRows)
                        {
                            var Time = Row.Time;
                            if (Row.NewTime != null && (Convert.ToDateTime(Row.NewTime).Hour != Convert.ToDateTime(Row.Time).Hour || Convert.ToDateTime(Row.NewTime).Minute != Convert.ToDateTime(Row.Time).Minute))
                                Time = Row.NewTime;
                            var StartDate = (DateTime)Row.StartDate;
                            if (Row.NewStartDate != null && Row.NewStartDate != Row.StartDate)
                                StartDate = (DateTime)Row.NewStartDate;
                            tblGuideConfirm NewGuide = new tblGuideConfirm()
                            {
                                GroupID = Row.GroupID,
                                GuideID = (int)Row.NewSelectedGuideID,
                                StartDate = StartDate,
                                Time = Time,
                                Salary = Row.GuideSalary,
                                GuideMisc = Row.GuideMisc,
                                GuideStepOn = Row.GuideStepOn,
                                SalaryPaid = Row.GuideSalaryPaid,
                                PaidAmt = Row.GuidePaidAmt,
                                EmployeeID = Row.EmployeeID,
                                AddCharge = Row.GuideAddCharge,
                                FirstPayment = Row.FirstPayAmt,
                                FirstPaymentMethod = Row.FirstPayMethod,
                                FirstPaymentDate = Row.FirstPayDate,
                                SecondPayment = Row.SecondPayAmt,
                                SecondPaymentMethod = Row.SecondPayMethod,
                                SecondPaymentDate = Row.SecondPayDate,
                                ThirdPayment = Row.ThirdPayAmt,
                                ThirdPaymentMethod = Row.ThirdPayMethod,
                                ThirdPaymentDate = Row.ThirdPayDate,
                            };
                            _context.tblGuideConfirms.Add(NewGuide);
                        }
                    }
                    if (Data.SaveRows.Any(row => row.NewVendorID != null && row.VendorID == 0 && row.NewStartDate != null && row.StartDate == null))
                    {
                        var SaveRows = Data.SaveRows.Where(row => row.NewVendorID != null && row.VendorID == 0 && row.NewStartDate != null && row.StartDate == null).ToList();
                        // New Attraction or Restaurant Confirm
                        foreach (var Row in SaveRows)
                        {
                            var Time = Row.Time;
                            if (Row.NewTime != null && (Convert.ToDateTime(Row.NewTime).Hour != Convert.ToDateTime(Row.Time).Hour || Convert.ToDateTime(Row.NewTime).Minute != Convert.ToDateTime(Row.Time).Minute))
                                Time = Row.NewTime;
                            tblBusConfirm newBus = new tblBusConfirm()
                            {
                                GroupID = Row.GroupID,
                                VendorID = (int)Row.NewVendorID,
                                StartDate = (DateTime)Row.NewStartDate,
                                Time = Time,
                                EmployeeID = Row.EmployeeID,
                                QuotaRate = Row.QuotaRate,
                                QuotaCurr = Row.QuotaCurr,
                                FinishDate = Row.FinishDate,
                                ConfirmDate = Row.ConfirmDate,
                                ServiceDetID = Row.ServiceID,
                                Airport = Row.Airport,
                                BusCount = Row.BusCount,
                                BusPrice = Row.BusPrice,
                                BusSize = Row.BusSize,
                                EndCity = Row.EndCity,
                                IsInvoice = Row.IsInvoice,
                                InvoicePrice = Row.InvoicePrice,
                                Pax = Row.IsInvoice == true ? Row.Pax : Row.Pax,
                                StatusID = Row.SelectedVendorStatus,
                                FirstPayment = Row.FirstPayAmt,
                                FirstPaymentMethod = Row.FirstPayMethod,
                                FirstPaymentDate = Row.FirstPayDate,
                                SecondPayment = Row.SecondPayAmt,
                                SecondPaymentMethod = Row.SecondPayMethod,
                                SecondPaymentDate = Row.SecondPayDate,
                                ThirdPayment = Row.ThirdPayAmt,
                                ThirdPaymentMethod = Row.ThirdPayMethod,
                                ThirdPaymentDate = Row.ThirdPayDate,
                                Notes = Row.Notes,
                            };
                            _context.tblBusConfirms.Add(newBus);
                        }
                    }
                    _context.SaveChanges();
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    Error.errorCode = 5643;
                    Error.Message = ex.Message;
                    logger.Error(ex.ToMessageAndCompleteStacktrace());
                    transaction.Rollback();
                }
            }
            return OperationSearchBus(Data, FilterData, PageNum, UserRegions, UserName);
        }
        public OperationTechProgGridBData SaveOperationTechProg(OperationTechProgGridBData Data, OperationTechProgFilterBData FilterData)
        {
            ErrorBInfo Error = new ErrorBInfo();
            using (var transaction = _context.Database.BeginTransaction(IsolationLevel.Serializable))
            {
                try
                {
                    var GroupID = _context.tblGroups.Where(grp => Data.GroupCode == grp.GroupCode).SingleOrDefault().GroupID;
                    var ChangedTechProg = _context.tblTechDetails.Where(techd => GroupID == techd.GroupID).ToList();
                    foreach (var TechProg in ChangedTechProg)
                    {
                        foreach (var Row in Data.SaveRows)
                        {
                            if (Row.Date == TechProg.Date && Row.OldTime == TechProg.Time && Row.GroupID == TechProg.GroupID)
                            {
                                TechProg.DetailID = Row.DetailID;
                                TechProg.Description = Row.Desc;
                                TechProg.Via = Row.Via;
                                TechProg.PrnFlg = Row.PrnFlag;
                                if (Row.Time != null && Row.Time != Row.OldTime)
                                {
                                    tblTechDetail NewTech = new tblTechDetail()
                                    {
                                        GroupID = TechProg.GroupID,
                                        Date = TechProg.Date,
                                        Time = Row.Time,
                                        GuideID = TechProg.GuideID,
                                        DetailID = Row.DetailID,
                                        VendorID = TechProg.VendorID,
                                        vcArrivalTime = TechProg.vcArrivalTime,
                                        Description = Row.Desc,
                                        Via = Row.Via,
                                        StateID = TechProg.StateID,
                                        Pax = TechProg.Pax,
                                        PaxPlus = TechProg.PaxPlus,
                                        Cost = TechProg.Cost,
                                        LineNo = TechProg.LineNo,
                                        PrnFlg = Row.PrnFlag,
                                        MissingFlg = TechProg.MissingFlg,
                                        City = TechProg.City,
                                        TechTypeID = TechProg.TechTypeID,
                                        Type = TechProg.Type,
                                    };
                                    _context.tblTechDetails.Remove(TechProg);
                                    _context.tblTechDetails.Add(NewTech);
                                }
                                break;
                            }
                        }
                    }
                    _context.SaveChanges();
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    Error.errorCode = 5643;
                    Error.Message = ex.Message;
                    logger.Error(ex.ToMessageAndCompleteStacktrace());
                    transaction.Rollback();
                }
            }
            return LoadOperationTechProg(Data.GroupCode, FilterData);
        }
        public OperationTechProgGridBData LoadOperationTechProg(string GroupCode, OperationTechProgFilterBData FilterData)
        {
             OperationTechProgGridBData TechProgBData = new OperationTechProgGridBData();
             TechProgBData.Error = new ErrorBInfo();
             try
             {
                 var FilterGroup = _context.tblGroups.AsQueryable();
                 var FilterTechDetails = _context.tblTechDetails.AsQueryable();
                 if (GroupCode != null && GroupCode.Length > 0)
                     FilterGroup = FilterGroup.Where(grp => grp.GroupCode == GroupCode);               
                 InitOperationTechProgGridBData(TechProgBData, FilterGroup, FilterTechDetails);
                 OperationTechProgFiltersInit(ref FilterTechDetails, FilterData);
                 TechProgBData.Rows = InitTechProgGridBData(FilterGroup, FilterTechDetails);
             }
             catch (Exception ex)
             {
                 TechProgBData.Error.errorCode = 2346;
                 TechProgBData.Error.Message = ex.Message;
                 logger.Error(ex.ToMessageAndCompleteStacktrace());
             }
            return TechProgBData;
        }
        public OperationTechProgGridBData ValidateOperationTechProg(string GroupCode, OperationTechProgFilterBData FilterData)
        {
            ErrorBInfo Error = new ErrorBInfo();
            using (var transaction = _context.Database.BeginTransaction())
            {
            var Group = _context.tblGroups.Where(grp => grp.GroupCode == GroupCode).SingleOrDefault();
            if (Group != null)
            {
                var VendorConfirm = _context.tblVendorConfirms.Where(Vconf => Vconf.GroupID == Group.GroupID && Vconf.StatusID == 2).ToList();
                var BusConfirm = _context.tblBusConfirms.Where(Bconf => Bconf.GroupID == Group.GroupID && Bconf.StatusID == 2).ToList();
                var GuideConfirm = _context.tblGuideConfirms.Where(Gconf => Gconf.GroupID == Group.GroupID).ToList();
                var AttrConfirm = _context.tblAttractionsConfirms.Where(Aconf => Aconf.GroupID == Group.GroupID && Aconf.StatusID == 2).ToList();
                var RestConfirm = _context.tblRestaurantsConfirms.Where(Rconf => Rconf.GroupID == Group.GroupID && Rconf.StatusID == 2).ToList();
                var VendorConfirmDetails = _context.tblVConfirmDetails.Where(VcDet => VcDet.GroupID == Group.GroupID).ToList();
                var MiscConfirm = _context.tblMiscConfirms.Where(Mconf => Mconf.GroupID == Group.GroupID && Mconf.StatusID == 2).ToList();
                var DetailInfo = (from det in _context.tblDetails
                                  from dettype in _context.tblDetailTypes
                                  from SerType in _context.tblServiceTypes
                                  where SerType.ServiceTypeID == det.ServiceTypeID 
                                  && det.DetailTypeID == dettype.DetailTypeID 
                                  && det.Active == true 
                                  && dettype.Active == true 
                                  && SerType.Active == true
                                  select new { VendorTypeId = dettype.VendorTypeID, DetailID = det.DetailID, ServiceTypeCode = SerType.ServiceTypeCode, DetailCode = det.DetailCode }).ToList();

                List<tblTechDetail> TechList = new List<tblTechDetail>();
                
                    var DelTech = _context.tblTechDetails.Where(tech => tech.GroupID == Group.GroupID).ToList();
                    // Hotel
                    var BreakfastTime = Convert.ToDateTime("07:00");
                    var LunchTime = Convert.ToDateTime("13:00");
                    var DinnerTime = Convert.ToDateTime("20:00");
                    foreach (var Vc in VendorConfirm)
                    {
                        var Nights = (Convert.ToDateTime(Vc.DepartureDate) - Vc.ArrivalDate).Days;
                        for (int ind = 1; ind <= Nights + 1; ind++)
                        {
                            if (VendorConfirmDetails.Any(VcDet => VcDet.VendorID == Vc.VendorID && VcDet.StartDate == Vc.ArrivalDate.AddDays(ind - 1) && VcDet.ProductID == 1 && VcDet.ServiceID == 6))
                            {
                                // new ABF in hotel
                                tblTechDetail TechDet = new tblTechDetail()
                                {
                                    City = Vc.ArrivalCity,
                                    Date = Vc.ArrivalDate.AddDays(ind - 1),
                                    Time = BreakfastTime.TimeOfDay,
                                    GroupID = Group.GroupID,
                                    VendorID = Vc.VendorID,
                                    Type = "Hotel Meal",
                                    EmployeeID = Vc.EmployeeID,
                                    DetailID = DetailInfo.Any(det => det.VendorTypeId == 1 && det.ServiceTypeCode == "Breakfast" && det.DetailCode == "ABFH") ? DetailInfo.Where(det => det.VendorTypeId == 1 && det.ServiceTypeCode == "Breakfast" && det.DetailCode == "ABFH").FirstOrDefault().DetailID : 0,
                                };
                                TechList.Add(TechDet);
                            }
                            if (VendorConfirmDetails.Any(VcDet => VcDet.VendorID == Vc.VendorID && VcDet.StartDate == Vc.ArrivalDate.AddDays(ind - 1) && VcDet.ProductID == 1 && VcDet.ServiceID == 7))
                            {
                                // new CBF in hotel
                                tblTechDetail TechDet = new tblTechDetail()
                                {
                                    City = Vc.ArrivalCity,
                                    Date = Vc.ArrivalDate.AddDays(ind - 1),
                                    Time = BreakfastTime.TimeOfDay,
                                    GroupID = Group.GroupID,
                                    VendorID = Vc.VendorID,
                                    Type = "Hotel Meal",
                                    EmployeeID = Vc.EmployeeID,
                                    DetailID = DetailInfo.Any(det => det.VendorTypeId == 1 && det.ServiceTypeCode == "Breakfast" && det.DetailCode == "CONH") ? DetailInfo.Where(det => det.VendorTypeId == 1 && det.ServiceTypeCode == "Breakfast" && det.DetailCode == "CONH").FirstOrDefault().DetailID : 0,
                                };
                                TechList.Add(TechDet);
                            }
                            if (VendorConfirmDetails.Any(VcDet => VcDet.VendorID == Vc.VendorID && VcDet.StartDate == Vc.ArrivalDate.AddDays(ind - 1) && VcDet.ProductID == 1 && VcDet.ServiceID == 70))
                            {
                                // new Lunch in hotel
                                tblTechDetail TechDet = new tblTechDetail()
                                {
                                    City = Vc.ArrivalCity,
                                    Date = Vc.ArrivalDate.AddDays(ind - 1),
                                    Time = LunchTime.TimeOfDay,
                                    GroupID = Group.GroupID,
                                    VendorID = Vc.VendorID,
                                    Type = "Hotel Meal",
                                    EmployeeID = Vc.EmployeeID,
                                    DetailID = DetailInfo.Any(det => det.VendorTypeId == 1 && det.ServiceTypeCode == "Lunch" && det.DetailCode == "LUNH") ? DetailInfo.Where(det => det.VendorTypeId == 1 && det.ServiceTypeCode == "Lunch" && det.DetailCode == "LUNH").FirstOrDefault().DetailID : 0,
                                };
                                TechList.Add(TechDet);
                            }
                            if (VendorConfirmDetails.Any(VcDet => VcDet.VendorID == Vc.VendorID && VcDet.StartDate == Vc.ArrivalDate.AddDays(ind - 1) && VcDet.ProductID == 1 && VcDet.ServiceID == 71))
                            {
                                // new Dinner in hotel
                                tblTechDetail TechDet = new tblTechDetail()
                                {
                                    City = Vc.ArrivalCity,
                                    Date = Vc.ArrivalDate.AddDays(ind - 1),
                                    Time = DinnerTime.TimeOfDay,
                                    GroupID = Group.GroupID,
                                    VendorID = Vc.VendorID,
                                    Type = "Hotel Meal",
                                    EmployeeID = Vc.EmployeeID,
                                    DetailID = DetailInfo.Any(det => det.VendorTypeId == 1 && det.ServiceTypeCode == "Dinner" && det.DetailCode == "DINH") ? DetailInfo.Where(det => det.VendorTypeId == 1 && det.ServiceTypeCode == "Dinner" && det.DetailCode == "DINH").FirstOrDefault().DetailID : 0,
                                };
                                TechList.Add(TechDet);
                            }

                            if (ind < Nights + 1)
                            {
                                tblTechDetail TechDet = new tblTechDetail()
                                {
                                    City = Vc.ArrivalCity,
                                    Date = Vc.ArrivalDate.AddDays(ind - 1),
                                    Time = Convert.ToDateTime("23:59").TimeOfDay,
                                    Description = Vc.Notes,
                                    GroupID = Group.GroupID,
                                    VendorID = Vc.VendorID,
                                    Type = "Hotel",
                                    EmployeeID = Vc.EmployeeID,
                                    DetailID = DetailInfo.Any(det => det.VendorTypeId == 1 && det.ServiceTypeCode == "Room") ? DetailInfo.Where(det => det.VendorTypeId == 1 && det.ServiceTypeCode == "Room").FirstOrDefault().DetailID : 0,
                                };
                                TechList.Add(TechDet);
                            }
                        }
                    }
                    // Bus
                    foreach (var bus in BusConfirm)
                    {
                        tblTechDetail TechDet = new tblTechDetail()
                        {
                            City = bus.StartCity,
                            Date = bus.StartDate,
                            Time = Convert.ToDateTime(bus.Time).TimeOfDay,
                            Description = bus.Notes,
                            GroupID = Group.GroupID,
                            VendorID = bus.VendorID,
                            Type = "Bus",
                            EmployeeID = bus.EmployeeID,
                            DetailID = (int)bus.ServiceDetID,
                        };
                        if(GuideConfirm.Any(guide=>guide.GroupID == bus.GroupID && guide.StartDate == bus.StartDate))
                            TechDet.GuideID = GuideConfirm.Where(guide => guide.GroupID == bus.GroupID && guide.StartDate == bus.StartDate).FirstOrDefault().GuideID;
                        
                        TechList.Add(TechDet);
                    }
                    // Attr
                    foreach (var Attr in AttrConfirm)
                    {
                        tblTechDetail TechDet = new tblTechDetail()
                        {
                            //City = Attr.city,
                            Date = Attr.StartDate,
                            Time = Convert.ToDateTime(Attr.Time).TimeOfDay,
                            Description = Attr.Notes,
                            GroupID = Group.GroupID,
                            VendorID = Attr.VendorID,
                            Type = "Attraction",
                            EmployeeID = Attr.EmployeeID,
                            DetailID = DetailInfo.Any(det => det.VendorTypeId == 4) ? DetailInfo.Where(det => det.VendorTypeId == 4).FirstOrDefault().DetailID : 0,
                        };
                        TechList.Add(TechDet);
                    }
                    // Rest
                    foreach (var Rest in RestConfirm)
                    {
                        tblTechDetail TechDet = new tblTechDetail()
                        {
                            //City = Rest.ar,
                            Date = Rest.StartDate,
                            Time = Convert.ToDateTime(Rest.Time).TimeOfDay,
                            Description = Rest.Notes,
                            GroupID = Group.GroupID,
                            VendorID = Rest.VendorID,
                            Type = "Restaurant",
                            EmployeeID = Rest.EmployeeID,
                            DetailID = DetailInfo.Any(det => det.VendorTypeId == 2) ? DetailInfo.Where(det => det.VendorTypeId == 2).FirstOrDefault().DetailID : 0,
                        };
                        TechList.Add(TechDet);
                    }
                    // Misc
                    List<int> MisclList = new List<int>() {5,6,7 };
                    foreach (var Misc in MiscConfirm)
                    {
                        tblTechDetail TechDet = new tblTechDetail()
                        {
                            //City = Attr.city,
                            Date = Misc.StartDate,
                            Time = Convert.ToDateTime(Misc.Time).TimeOfDay,
                            Description = Misc.Notes,
                            GroupID = Group.GroupID,
                            VendorID = Misc.VendorID,
                            Type = Misc.IsComp == true ? "Misc Comp" : "Misc",
                            EmployeeID = Misc.EmployeeID,
                            DetailID = Convert.ToInt32(Misc.ServiceDetID),
                        };
                        TechList.Add(TechDet);
                    }
                    TechList = TechList.OrderBy(tech => tech.Date).ThenBy(tech => tech.Time).ToList();
                    // Update techProg Date
                    Group.TechProgUpdt = false;
                    Group.TechProgUpdtDate = DateTime.Now;

                    // Check for same date time 
                    var CheckTech = TechList.GroupBy(tech => new { tech.GroupID, tech.Date, tech.Time }).ToList();
                    StringBuilder Mess = new StringBuilder();
                    foreach(var TechDet in CheckTech)
                    {
                        var CurrentTech = TechList.Where(tech => tech.GroupID == TechDet.Key.GroupID && tech.Date == TechDet.Key.Date && tech.Time == TechDet.Key.Time).ToList();
                        if (CurrentTech.Count > 1)
                        {
                            var TabStrList = CurrentTech.GroupBy(tech => tech.Type).Select(tech=>tech.Key).ToList();
                            string TabStr = "";
                            foreach (var str in TabStrList)
                                TabStr = TabStr + str + ", ";
                            Mess.Append(string.Format("Same Date and Time activity on {0} {1}, {2} \n", CurrentTech[0].Date.ToString("dd/MMM/yy"), new DateTime().Add(CurrentTech[0].Time).ToString("hh:mm tt"), TabStr));
                        }
                    }
                    try
                    {
                        _context.tblTechDetails.RemoveRange(DelTech);
                        _context.tblTechDetails.AddRange(TechList);
                        _context.SaveChanges();
                        transaction.Commit();
                    }
                    catch (DbUpdateException ex)
                    {
                        Error.errorCode = 779;
                        Error.Message = Mess.ToString();
                        logger.Error(ex.ToMessageAndCompleteStacktrace());
                        transaction.Rollback();
                    }
                    catch (Exception ex)
                    {
                        Error.errorCode = 778;
                        Error.Message = ex.Message;
                        logger.Error(ex.ToMessageAndCompleteStacktrace());
                        transaction.Rollback();
                    }
                }
            }
            var Data = LoadOperationTechProg(GroupCode, FilterData);
            if (Error.errorCode != 0)
                Data.Error = Error;
            return Data;
        }
        public OperationGroupCheckListGridBData LoadOperationGroupCheckList(int PageNum, List<string> UserRegions, string UserName)
        {
            OperationGroupCheckListGridBData GroupCheckListData = new OperationGroupCheckListGridBData();
            var Group = _context.tblGroups.AsQueryable();
            var Customer = _context.tblCustomers.AsQueryable();
            InitOperationGroupCheckListGridBData(GroupCheckListData, Group, Customer, UserName);
            GroupCheckListData.Rows = InitGroupCheckListGridBData(PageNum, Group, Customer, UserRegions, UserName);
            return GroupCheckListData;
        }
        public OperationGirGroupPricesGridBData OperationLoadGirPrices(int QuotaID, int GroupID)
        {
            OperationGirGroupPricesGridBData PriceBData = new OperationGirGroupPricesGridBData();
            PriceBData.Rows = new List<OperationGirGroupPricesGridRowBData>();

            PriceBData.Rows = (from grp in _context.tblGroups
                               from cus in _context.tblCustomers
                               from GirDet in _context.tblGirGroupDetails
                               where grp.GroupID == GirDet.GroupID 
                               && GirDet.GroupID == GroupID
                               && cus.CustomerID == GirDet.CustomerID
                               && cus.Active == true
                               select new OperationGirGroupPricesGridRowBData()
                               {
                                   GroupID = grp.GroupID,
                                   GroupCode = grp.GroupCode,
                                   GroupName = grp.GroupName,
                                   CustomerID = cus.CustomerID,
                                   ArrivalDate = grp.ArrivalDate,
                                   Customer = cus.OrganizationName,
                                   PricePerPerson = GirDet.PricePerPerson,
                                   PriceFBoard = GirDet.PriceFullBoard,
                                   PriceSingleSup = GirDet.PriceSingleSupp,
                                   PricePerPersonCad = GirDet.PricePerPersonCad,
                                   PriceFBoardCad = GirDet.PriceFullBoardCad,
                                   PriceSingleSupCad = GirDet.PriceSingleSuppCad,
                               }).ToList();
            return PriceBData;
        }
        public OperationGirGroupPricesGridBData OperationSaveGirPrices(OperationGirGroupPricesGridBData Data)
        {
            ErrorBInfo Error = new ErrorBInfo();
            using (var transaction = _context.Database.BeginTransaction())
            {
                try
                {
                    var GroupIds = Data.Rows.Select(row => row.GroupID).ToList();
                    var ChangedGirDet = _context.tblGirGroupDetails.Where(GirGrp => GroupIds.Contains(GirGrp.GroupID)).ToList();
                    foreach (var GirGroup in ChangedGirDet)
                    {
                        var Row = Data.Rows.Where(row => row.GroupID == GirGroup.GroupID && row.CustomerID == GirGroup.CustomerID).SingleOrDefault();
                        if (Row != null)
                        {
                            GirGroup.PricePerPerson = Row.PricePerPerson;
                            GirGroup.PriceSingleSupp = Row.PriceSingleSup;
                            GirGroup.PriceFullBoard = Row.PriceFBoard;
                            GirGroup.PricePerPersonCad = Row.PricePerPersonCad;
                            GirGroup.PriceSingleSuppCad = Row.PriceSingleSupCad;
                            GirGroup.PriceFullBoardCad = Row.PriceFBoardCad;
                        }
                    }
                    _context.SaveChanges();
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    Error.errorCode = 6734;
                    Error.Message = ex.Message;
                    logger.Error(ex.ToMessageAndCompleteStacktrace());
                    transaction.Rollback();
                }
            }

            OperationGirGroupPricesGridBData GridBData = new OperationGirGroupPricesGridBData();
            return GridBData;
        }
        public OperationHotelGridBData OperationFilterHotel(OperationHotelGridBData Data, OperationHotelFilterBData FilterData, int PageNum, List<string> UserRegions, string UserName)
        {
            OperationHotelGridBData Hoteldata = new OperationHotelGridBData();
            Hoteldata.Error = new ErrorBInfo();
            try
            {
                var FilterGroup = _context.tblGroups.AsQueryable();
                var FilterCustomer = _context.tblCustomers.AsQueryable();
                var FilterCountry = _context.tblCountries.AsQueryable();
                var FilterVendorConfirm = _context.tblVendorConfirms.AsQueryable();
                var FilterVendor = _context.tblVendors.AsQueryable();
                var FilterQuotaHotel = _context.tblQuotaHotels.AsQueryable();

                if (Data.SearchGroupName != null && Data.SearchGroupName.Length > 0)
                    FilterGroup = FilterGroup.Where(grp => grp.GroupName.Contains(Data.SearchGroupName));
                if (Data.SearchGroupCode != null && Data.SearchGroupCode.Length > 0)
                    FilterGroup = FilterGroup.Where(grp => grp.GroupCode.Contains(Data.SearchGroupCode));
                if (Data.SearchCheckInFromDate != null)
                    FilterVendorConfirm = FilterVendorConfirm.Where(vconf => vconf.ArrivalDate >= Data.SearchCheckInFromDate);
                if (Data.SearchCheckInToDate != null)
                    FilterVendorConfirm = FilterVendorConfirm.Where(vconf => vconf.ArrivalDate <= Data.SearchCheckInToDate);
                if (Data.SearchCheckOutFromDate != null)
                    FilterVendorConfirm = FilterVendorConfirm.Where(vconf => vconf.DepartureDate >= Data.SearchCheckOutFromDate);
                if (Data.SearchCheckOutToDate != null)
                    FilterVendorConfirm = FilterVendorConfirm.Where(vconf => vconf.DepartureDate <= Data.SearchCheckOutToDate);
                if (Data.SelectedSearchArrivalCity != null)
                    FilterVendorConfirm = FilterVendorConfirm.Where(vconf => vconf.ArrivalCity.Contains(Data.SelectedSearchArrivalCity));
                if (Data.SelectedSearchDepartureCity != null)
                    FilterGroup = FilterGroup.Where(grp => grp.DepartureCity.Contains(Data.SelectedSearchDepartureCity));
                if (Data.SearchCustomer != null && Data.SearchCustomer.Length > 0)
                    FilterCustomer = FilterCustomer.Where(cust => cust.OrganizationName == Data.SearchCustomer);
                if (Data.SelectedSearchNationality != null)
                    FilterCountry = FilterCountry.Where(cntry => cntry.CountryID == Data.SelectedSearchNationality);
                if (Data.SearchVendorName != null && Data.SearchVendorName.Length > 0)
                    FilterVendor = FilterVendor.Where(vend => vend.VendorName == Data.SearchVendorName);
                if (Data.SearchFlightNo != null && Data.SearchFlightNo.Length > 0)
                    FilterGroup = FilterGroup.Where(grp => grp.FlightInfo == Data.SearchFlightNo);
                if (Data.SelectedSearchStatus != null)
                    FilterGroup = FilterGroup.Where(grp => grp.StatusID == Data.SelectedSearchStatus);
                if (Data.SearchEmployeeID != 0)
                    FilterVendorConfirm = FilterVendorConfirm.Where(vconf => vconf.EmployeeID == Data.SearchEmployeeID);

                InitOperationHotelGridBData(Hoteldata, FilterVendorConfirm, FilterGroup, UserName);
                OperationHotelFiltersInit(ref FilterGroup, ref FilterVendor, ref FilterVendorConfirm, FilterData);
                int Count = 0;
                Hoteldata.Rows = InitHotelGridBData(PageNum, FilterGroup, FilterCustomer, FilterCountry, FilterVendorConfirm, FilterVendor, FilterQuotaHotel, UserRegions, UserName, ref Count);
                Hoteldata.Count = Count;
            }
            catch (Exception ex)
            {
                Hoteldata.Error.errorCode = 2346;
                Hoteldata.Error.Message = ex.Message;
                logger.Error(ex.ToMessageAndCompleteStacktrace());
            }
            return Hoteldata;
        }
        public OperationRoomGridBData OperationFilterRoom(OperationRoomFilterBData Data, int PageNum, List<string> UserRegions)
        {
            OperationRoomGridBData Roomdata = new OperationRoomGridBData();
            try
            {
                InitOperationRoomGridBData(Roomdata, null, 0);
                var FilterRoom = _context.tblGroupRooms.AsQueryable();
                var FilterGroup = _context.tblGroups.AsQueryable();
                var FilterCustomer = _context.tblCustomers.AsQueryable();
                // filtering customer
                if (Data.FilterRoomCustomerVal != null)
                    FilterGroup = FilterGroup.Where(grp => Data.FilterRoomCustomerVal.Contains(grp.CustomerID));
                // filtering Room Type
                if (Data.FilterRoomTypeVal != null)
                    FilterRoom = FilterRoom.Where(room => Data.FilterRoomTypeVal.Contains(room.ServiceID));
                // filtering Room Title
                if (Data.FilterRoomTitleVal != null)
                    FilterRoom = FilterRoom.Where(room => Data.FilterRoomTitleVal.Contains(room.Title));
                List<OperationRoomGirGridRowBData> GirRow;
                InitRoomFilters(Data, ref FilterRoom, ref FilterGroup);
                Roomdata.Rows = InitRoomGridBData(PageNum, FilterRoom, FilterGroup, FilterCustomer, out GirRow, UserRegions);
                Roomdata.GirRows = GirRow;
                if (FilterGroup.SingleOrDefault() != null)
                    Roomdata.IsGir = FilterGroup.SingleOrDefault().IsGir != null ? Convert.ToBoolean(FilterGroup.SingleOrDefault().IsGir) : false;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToMessageAndCompleteStacktrace());
            }
            return Roomdata;
        }
        public OperationRoomGridBData RemoveOperationRooms(OperationRoomFilterBData Data, int GroupId, int LineNo, int PageNum, List<string> UserRegions)
        {
            OperationRoomGridBData Roomdata = new OperationRoomGridBData();
            ErrorBInfo Error = new ErrorBInfo();
            using (var transaction = _context.Database.BeginTransaction(IsolationLevel.Serializable))
            {
                try
                {
                    var RemoveR = _context.tblGroupRooms.Where(room => room.GroupID == GroupId && room.LineNo == LineNo).FirstOrDefault();
                    var Group = _context.tblGroups.Where(grp => grp.GroupID == GroupId).SingleOrDefault();

                    var AttrConfirm = _context.tblAttractionsConfirms.Where(att => att.GroupID == GroupId).ToList();
                    var RestConfirm = _context.tblRestaurantsConfirms.Where(rest => rest.GroupID == GroupId).ToList();
                    var BusConfirm = _context.tblBusConfirms.Where(bus => bus.GroupID == GroupId).ToList();
                    var MiscConfirm = _context.tblMiscConfirms.Where(misc => misc.GroupID == GroupId).ToList();
                  
                    if (Group != null && Group.IsGir == false)
                    {
                        if (RemoveR.ServiceID == 1)
                        {
                            var ConnectedSSInvoiceUsd = _context.tblGroupInvoices.Where(inv => inv.GroupID == GroupId && inv.Currency == "USD" && inv.Description == "Single Supplement").FirstOrDefault();
                            if (ConnectedSSInvoiceUsd != null)
                            {
                                ConnectedSSInvoiceUsd.Quantity = ConnectedSSInvoiceUsd.Quantity - 1;
                                ConnectedSSInvoiceUsd.Price = Math.Round(SingleSupPriceByCurr("USD", Group.QuotaID));
                                ConnectedSSInvoiceUsd.PriceChange = ConnectedSSInvoiceUsd.Price;
                                if (ConnectedSSInvoiceUsd.DebCre == false)
                                    ConnectedSSInvoiceUsd.Debit = ConnectedSSInvoiceUsd.Quantity * ConnectedSSInvoiceUsd.Price;
                                if (ConnectedSSInvoiceUsd.DebCre == true)
                                    ConnectedSSInvoiceUsd.Credit = ConnectedSSInvoiceUsd.Quantity * ConnectedSSInvoiceUsd.Price;
                            }
                            var ConnectedSSInvoiceCad = _context.tblGroupInvoices.Where(inv => inv.GroupID == GroupId && inv.Currency == "CAD" && inv.Description == "Single Supplement").FirstOrDefault();
                            if (ConnectedSSInvoiceCad != null)
                            {
                                ConnectedSSInvoiceCad.Quantity = ConnectedSSInvoiceCad.Quantity - 1;
                                ConnectedSSInvoiceCad.Price = Math.Round(SingleSupPriceByCurr("CAD", Group.QuotaID));
                                ConnectedSSInvoiceCad.PriceChange = ConnectedSSInvoiceCad.Price;
                                if (ConnectedSSInvoiceCad.DebCre == false)
                                    ConnectedSSInvoiceCad.Debit = ConnectedSSInvoiceCad.Quantity * ConnectedSSInvoiceCad.Price;
                                if (ConnectedSSInvoiceCad.DebCre == true)
                                    ConnectedSSInvoiceCad.Credit = ConnectedSSInvoiceCad.Quantity * ConnectedSSInvoiceCad.Price;
                            }
                        }
                        if (RemoveR.ServiceID > 1)
                        {
                            var ConnectedPPInvoiceUsd = _context.tblGroupInvoices.Where(inv => inv.GroupID == GroupId && inv.Currency == "USD" && inv.Description == "Per Person").FirstOrDefault();
                            if (ConnectedPPInvoiceUsd != null)
                            {
                                ConnectedPPInvoiceUsd.Quantity = ConnectedPPInvoiceUsd.Quantity - OperationRoomPaxByServiceId(RemoveR.ServiceID);
                                ConnectedPPInvoiceUsd.Price = Math.Round(Convert.ToDecimal(PerPersonPriceByPax(ConnectedPPInvoiceUsd.Quantity, "USD", Group.QuotaID)));
                                ConnectedPPInvoiceUsd.PriceChange = ConnectedPPInvoiceUsd.Price;
                                if (ConnectedPPInvoiceUsd.DebCre == false)
                                    ConnectedPPInvoiceUsd.Debit = ConnectedPPInvoiceUsd.Quantity * ConnectedPPInvoiceUsd.Price;
                                if (ConnectedPPInvoiceUsd.DebCre == true)
                                    ConnectedPPInvoiceUsd.Credit = ConnectedPPInvoiceUsd.Quantity * ConnectedPPInvoiceUsd.Price;
                            }
                            var ConnectedPPInvoiceCad = _context.tblGroupInvoices.Where(inv => inv.GroupID == GroupId && inv.Currency == "CAD" && inv.Description == "Per Person").FirstOrDefault();
                            if (ConnectedPPInvoiceCad != null)
                            {
                                ConnectedPPInvoiceCad.Quantity = ConnectedPPInvoiceCad.Quantity - OperationRoomPaxByServiceId(RemoveR.ServiceID);
                                ConnectedPPInvoiceCad.Price = Math.Round(Convert.ToDecimal(PerPersonPriceByPax(ConnectedPPInvoiceCad.Quantity, "USD", Group.QuotaID)));
                                ConnectedPPInvoiceCad.PriceChange = ConnectedPPInvoiceCad.Price;
                                if (ConnectedPPInvoiceCad.DebCre == false)
                                    ConnectedPPInvoiceCad.Debit = ConnectedPPInvoiceCad.Quantity * ConnectedPPInvoiceCad.Price;
                                if (ConnectedPPInvoiceCad.DebCre == true)
                                    ConnectedPPInvoiceCad.Credit = ConnectedPPInvoiceCad.Quantity * ConnectedPPInvoiceCad.Price;
                            }
                        }
                    }
                    if (Group != null && Group.IsGir == true)
                    {
                        var ConnectedGirInvoices = _context.tblGirGroupInvoices.Where(GInv => GInv.GroupID == Group.GroupID && GInv.CustomerID == RemoveR.CustomerID).ToList();
                        var PerPersUsa = ConnectedGirInvoices.Where(Inv => Inv.Currency == "USD" && Inv.Description == "Per Person").FirstOrDefault();
                        if (PerPersUsa != null)
                        {
                            PerPersUsa.Quantity = PerPersUsa.Quantity - RemoveR.NoOfPerson;
                            if (PerPersUsa.DebCre == true)
                                PerPersUsa.Credit = Convert.ToDecimal(PerPersUsa.PriceChange) * PerPersUsa.Quantity;
                            if (PerPersUsa.DebCre == false)
                                PerPersUsa.Debit = Convert.ToDecimal(PerPersUsa.PriceChange) * PerPersUsa.Quantity;
                        }
                        var PerPersCad = ConnectedGirInvoices.Where(Inv => Inv.Currency == "CAD" && Inv.Description == "Per Person").FirstOrDefault();
                        if (PerPersCad != null)
                        {
                            PerPersCad.Quantity = PerPersCad.Quantity - RemoveR.NoOfPerson;
                            if (PerPersCad.DebCre == true)
                                PerPersCad.Credit = Convert.ToDecimal(PerPersCad.PriceChange) * PerPersCad.Quantity;
                            if (PerPersCad.DebCre == false)
                                PerPersCad.Debit = Convert.ToDecimal(PerPersCad.PriceChange) * PerPersCad.Quantity;
                        }
                        var FullBUsa = ConnectedGirInvoices.Where(Inv => Inv.Currency == "USD" && Inv.Description == "Full Board").FirstOrDefault();
                        if (FullBUsa != null && RemoveR.FullBoard == true)
                        {
                            FullBUsa.Quantity = FullBUsa.Quantity - 1;
                            if (FullBUsa.DebCre == true)
                                FullBUsa.Credit = Convert.ToDecimal(FullBUsa.PriceChange) * FullBUsa.Quantity;
                            if (FullBUsa.DebCre == false)
                                FullBUsa.Debit = Convert.ToDecimal(FullBUsa.PriceChange) * FullBUsa.Quantity;
                        }
                        var FullBCad = ConnectedGirInvoices.Where(Inv => Inv.Currency == "CAD" && Inv.Description == "Full Board").FirstOrDefault();
                        if (FullBCad != null && RemoveR.FullBoard == true)
                        {
                            FullBCad.Quantity = FullBCad.Quantity - 1;
                            if (FullBCad.DebCre == true)
                                FullBCad.Credit = Convert.ToDecimal(FullBCad.PriceChange) * FullBCad.Quantity;
                            if (FullBCad.DebCre == false)
                                FullBCad.Debit = Convert.ToDecimal(FullBCad.PriceChange) * FullBCad.Quantity;
                        }
                        var SsupUsa = ConnectedGirInvoices.Where(Inv => Inv.Currency == "USD" && Inv.Description == "Single Supplement").FirstOrDefault();
                        if (SsupUsa != null && RemoveR.NoOfPerson == 1)
                        {
                            SsupUsa.Quantity = SsupUsa.Quantity - 1;
                            if (SsupUsa.DebCre == true)
                                SsupUsa.Credit = Convert.ToDecimal(SsupUsa.PriceChange) * SsupUsa.Quantity;
                            if (SsupUsa.DebCre == false)
                                SsupUsa.Debit = Convert.ToDecimal(SsupUsa.PriceChange) * SsupUsa.Quantity;
                        }
                        var SsupCad = ConnectedGirInvoices.Where(Inv => Inv.Currency == "CAD" && Inv.Description == "Single Supplement").FirstOrDefault();
                        if (SsupCad != null && RemoveR.NoOfPerson == 1)
                        {
                            SsupCad.Quantity = SsupCad.Quantity - 1;
                            if (SsupCad.DebCre == true)
                                SsupCad.Credit = Convert.ToDecimal(SsupCad.PriceChange) * SsupCad.Quantity;
                            if (SsupCad.DebCre == false)
                                SsupCad.Debit = Convert.ToDecimal(SsupCad.PriceChange) * SsupCad.Quantity;
                        }
                    }

                    foreach (var att in AttrConfirm)
                        att.Pax = (short)(Convert.ToInt16(att.Pax) - OperationRoomPaxByServiceId(RemoveR.ServiceID));
                    foreach (var rest in RestConfirm)
                        rest.Pax = (short)(Convert.ToInt16(rest.Pax) - OperationRoomPaxByServiceId(RemoveR.ServiceID));
                    foreach (var bus in BusConfirm)
                        bus.Pax = (short)(Convert.ToInt16(bus.Pax) - OperationRoomPaxByServiceId(RemoveR.ServiceID));
                    foreach (var misc in MiscConfirm)
                        misc.Pax = (short)(Convert.ToInt16(misc.Pax) - OperationRoomPaxByServiceId(RemoveR.ServiceID));

                    _context.tblGroupRooms.Remove(RemoveR);
                    _context.SaveChanges();
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    Error.Message = ex.Message;
                    Error.errorCode = 323;
                    logger.Error(ex.ToMessageAndCompleteStacktrace());
                    transaction.Rollback();
                }
            }
            InitOperationRoomGridBData(Roomdata, null, GroupId);
            var FilterRoom = _context.tblGroupRooms.AsQueryable();
            var FilterGroup = _context.tblGroups.AsQueryable();
            var FilterCustomer = _context.tblCustomers.AsQueryable();
            InitRoomFilters(Data, ref FilterRoom, ref FilterGroup);

            List<OperationRoomGirGridRowBData> GirRow;
            Roomdata.Rows = InitRoomGridBData(PageNum, FilterRoom, FilterGroup, FilterCustomer, out GirRow, UserRegions);
            InitOperationRoomGridBData(Roomdata, null, GroupId, ref GirRow);
            Roomdata.GirRows = GirRow;
            if (FilterGroup.SingleOrDefault() != null)
                Roomdata.IsGir = FilterGroup.SingleOrDefault().IsGir != null ? Convert.ToBoolean(FilterGroup.SingleOrDefault().IsGir) : false;
            Roomdata.Error = Error;
            return Roomdata;
        }
        public Dictionary<int, string> FindKeywordInEntity(string PropName, string keyword, List<string> UserRegions)
        {
            List<int> QuotaIDs = _context.tblQuotations.Where(quota => quota.Active == true && UserRegions.Contains(quota.Region)).Select(quota => quota.QuotaID).ToList();
            List<int> CustomerIDs = _context.tblGroups.Where(grp => QuotaIDs.Contains((int)grp.QuotaID)).Select(grp => grp.CustomerID).ToList();
            Dictionary<int, string> RetVal = new Dictionary<int, string>();
            try
            {
                if (PropName == "GroupName")
                {
                    RetVal = _context.tblGroups.Where(grp => grp.GroupName.Contains(keyword) && QuotaIDs.Contains((int)grp.QuotaID)).Select(grp => new { grp.GroupID, grp.GroupName }).Take(10).ToDictionary(grp => grp.GroupID, grp => grp.GroupName);
                    return RetVal;
                }
                if (PropName == "GroupCode")
                {
                    RetVal = _context.tblGroups.Where(grp => grp.GroupCode.Contains(keyword) && QuotaIDs.Contains((int)grp.QuotaID)).Select(grp => new { grp.GroupID, grp.GroupCode }).Take(10).ToDictionary(grp => grp.GroupID, grp => grp.GroupCode);
                    return RetVal;
                }
                if (PropName == "CustomerOrgName")
                {
                    RetVal = _context.tblCustomers.Where(cust => cust.OrganizationName.Contains(keyword) && cust.Active == true && CustomerIDs.Contains(cust.CustomerID)).Select(cust => new { cust.CustomerID, cust.OrganizationName }).Take(10).ToDictionary(cust => cust.CustomerID, cust => cust.OrganizationName);
                    return RetVal;
                }
                if (PropName == "VendorName")
                {
                    RetVal = _context.tblVendors.Where(vnd => vnd.VendorName.Contains(keyword) && vnd.Active == true && vnd.VendorTypeID == 1).Select(vnd => new { vnd.VendorID, vnd.VendorName }).Take(10).ToDictionary(vnd => vnd.VendorID, vnd => vnd.VendorName);
                    return RetVal;
                }
                if (PropName == "AttrRestName")
                {
                    RetVal = _context.tblVendors.Where(vnd => vnd.VendorName.Contains(keyword) && vnd.Active == true && (vnd.VendorTypeID == 2 || vnd.VendorTypeID == 4 || vnd.VendorTypeID == 5)).Select(vnd => new { vnd.VendorID, vnd.VendorName }).Take(10).ToDictionary(vnd => vnd.VendorID, vnd => vnd.VendorName);
                    return RetVal;
                }
                if (PropName == "OperEmployee")
                {
                    RetVal = (from emp in _context.tblEmployees
                              where emp.Active == true && (emp.FirstName.Contains(keyword) || emp.LastName.Contains(keyword))
                              orderby emp.FirstName, emp.LastName
                              select new { EmployeeID = emp.EmployeeID, Employee = emp.FirstName + " " + emp.LastName }).Take(10).ToDictionary(emp => emp.EmployeeID, emp => emp.Employee);
                    return RetVal;
                }
                if (PropName == "BusName")
                {
                    RetVal = _context.tblVendors.Where(vnd => vnd.VendorName.Contains(keyword) && vnd.Active == true && vnd.VendorTypeID == 3).Select(vnd => new { vnd.VendorID, vnd.VendorName }).Take(10).ToDictionary(vnd => vnd.VendorID, vnd => vnd.VendorName);
                    return RetVal;
                }
                if (PropName == "MiscName")
                {
                    RetVal = _context.tblVendors.Where(vnd => vnd.VendorName.Contains(keyword) && vnd.Active == true && (vnd.VendorTypeID != 1 && vnd.VendorTypeID != null && vnd.VendorTypeID != 0)).Select(vnd => new { vnd.VendorID, vnd.VendorName }).Take(10).ToDictionary(vnd => vnd.VendorID, vnd => vnd.VendorName);
                    return RetVal;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToMessageAndCompleteStacktrace());
            }
            return RetVal;
        }
        public OperationRoomSearchGridBData OperationRoomSearchComplete(string PropName, string keyword, List<string> UserRegions)
        {
            OperationRoomSearchGridBData RetVal = new OperationRoomSearchGridBData();
            RetVal.Rows = new List<OperationRoomSearchGridRowBData>();
            RetVal.ControlName = PropName;
            try
            {
                if (PropName == "GroupName")
                {
                    RetVal.Rows = (from grp in _context.tblGroups
                                   from cust in _context.tblCustomers
                                   from quota in _context.tblQuotations
                                   where grp.QuotaID == quota.QuotaID && UserRegions.Contains(quota.Region)
                                   && grp.CustomerID == cust.CustomerID
                                   && cust.Active == true
                                   && grp.GroupName.Contains(keyword)
                                   select new OperationRoomSearchGridRowBData { GroupId = grp.GroupID, GroupName = grp.GroupName, GroupCode = grp.GroupCode, Customer = cust.OrganizationName, IsGir = grp.IsGir }).Take(10).ToList();
                    return RetVal;
                }
                if (PropName == "GroupCode")
                {
                    RetVal.Rows = (from grp in _context.tblGroups
                                   from cust in _context.tblCustomers
                                   from quota in _context.tblQuotations
                                   where grp.QuotaID == quota.QuotaID && UserRegions.Contains(quota.Region)
                                   && grp.CustomerID == cust.CustomerID
                                   && cust.Active == true
                                   && grp.GroupCode.Contains(keyword)
                                   select new OperationRoomSearchGridRowBData { GroupId = grp.GroupID, GroupName = grp.GroupName, GroupCode = grp.GroupCode, Customer = cust.OrganizationName, IsGir = grp.IsGir }).Take(10).ToList();
                    return RetVal;
                }
                if (PropName == "Customer")
                {
                    RetVal.Rows = (from grp in _context.tblGroups
                                   from cust in _context.tblCustomers
                                   from quota in _context.tblQuotations
                                   where grp.QuotaID == quota.QuotaID && UserRegions.Contains(quota.Region)
                                   && grp.CustomerID == cust.CustomerID
                                   && cust.Active == true
                                   && cust.OrganizationName.Contains(keyword)
                                   select new OperationRoomSearchGridRowBData { GroupId = grp.GroupID, GroupName = grp.GroupName, GroupCode = grp.GroupCode, Customer = cust.OrganizationName, IsGir = grp.IsGir }).Take(10).ToList();
                    return RetVal;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToMessageAndCompleteStacktrace());
            }
            return RetVal;
        }
        public OperationVendorHotelGridBData OperationVendorHotelGridLoad(int GroupID)
        {
            OperationVendorHotelGridBData VendHotelGrid = new OperationVendorHotelGridBData();
            var VendConf = _context.tblVendorConfirms.Where(vend => vend.GroupID == GroupID && vend.StatusID == 2).AsQueryable();
            InitOperVendorHotelGridBData(ref VendHotelGrid, ref VendConf);
            return VendHotelGrid;
        }
        public OperationGVendorRoomGridBData OperationGroupVendorGridLoad(int GroupID, int VendorID)
        {
            var VConfRoom = _context.tblVConfirmRooms.AsQueryable();
            VConfRoom = VConfRoom.Where(vroom => vroom.GroupID == GroupID && vroom.VendorID == VendorID);
            var VConf = _context.tblVendorConfirms.AsQueryable();
            VConf = VConf.Where(vconf => vconf.GroupID == GroupID && vconf.VendorID == VendorID);
            return InitOperationGroupVendorGridBData(VConfRoom, VConf);

        }
        public OperationGVendorRoomGridBData SaveOperationGroupVendorRooms(OperationGVendorRoomGridBData Data)
        {
            ErrorBInfo Error = new ErrorBInfo();
            var GroupID = Data.Rows.Select(row => row.GroupID).ToList();
            var VendorID = Data.Rows.Select(row => row.VendorID).ToList();
            var LineNo = Data.Rows.Select(row => row.LineNo).ToList();
            var VConfRommUpd = _context.tblVConfirmRooms.Where(VCRoom => GroupID.Contains(VCRoom.GroupID) && VendorID.Contains(VCRoom.VendorID) && VCRoom.ArrivalDate == Data.ArrivalDate && LineNo.Contains(VCRoom.LineNo)).ToList();
            using (var transaction = _context.Database.BeginTransaction(IsolationLevel.Serializable))
            {
                try
                {
                    var VendConf = _context.tblVendorConfirms.Where(Vc => Vc.GroupID == Data.GroupID && Vc.VendorID == Data.VendorID && Vc.ArrivalDate == Data.ArrivalDate).SingleOrDefault();
                    if (VendConf != null)
                    {
                        VendConf.RoomListEditNotes = Data.RoomListEditNotes;
                        VendConf.PorterageFlag = Data.PorterageFlag;
                        VendConf.PorterageNotes = Data.PorterageNotes;
                    }
                    foreach (var RoomUpd in VConfRommUpd)
                    {
                        var row = Data.Rows.Where(Row => Row.GroupID == RoomUpd.GroupID && Row.VendorID == RoomUpd.VendorID && Row.LineNo == RoomUpd.LineNo).SingleOrDefault();
                        if (row != null)
                        {
                            RoomUpd.CheckInDate = row.ArrivalDate;
                            RoomUpd.CheckOutDate = row.DepartureDate;
                            RoomUpd.ServiceID = row.ServiceID;
                            RoomUpd.Title = row.Title;
                            RoomUpd.NoOfPerson = OperationRoomPaxByServiceId(row.ServiceID);
                            RoomUpd.Names = row.Names;
                            RoomUpd.Notes = row.Notes;
                        }
                    }
                    // new rows
                    int LineNewNo = 0;
                    if (Data.Rows.Any(row => row.VendorID == 0))
                        LineNewNo = _context.tblVConfirmRooms.Any(VCRoom => VCRoom.GroupID == Data.GroupID && VCRoom.VendorID == Data.VendorID) ? _context.tblVConfirmRooms.Where(VCRoom => VCRoom.GroupID == Data.GroupID && VCRoom.VendorID == Data.VendorID).Max(VCRoom => VCRoom.LineNo) + 1 : 1;
                    var NewVendConfRoomList = new List<tblVConfirmRoom>();
                    foreach (var NewRow in Data.Rows)
                    {
                        if (NewRow.VendorID == 0 && NewRow.ServiceID != 0)
                        {
                            tblVConfirmRoom VCRoom = new tblVConfirmRoom()
                            {
                                GroupID = Data.GroupID,
                                VendorID = Data.VendorID,
                                ServiceID = NewRow.ServiceID,
                                Title = NewRow.Title,
                                NoOfPerson = OperationRoomPaxByServiceId(NewRow.ServiceID),
                                Names = NewRow.Names,
                                Notes = NewRow.Notes,
                                LineNo = LineNewNo,
                                CheckInDate = NewRow.ArrivalDate != null ? NewRow.ArrivalDate : VendConf.ArrivalDate,
                                CheckOutDate = NewRow.DepartureDate != null ? NewRow.DepartureDate : VendConf.DepartureDate,
                                ArrivalDate = Data.ArrivalDate,
                            };
                            NewVendConfRoomList.Add(VCRoom);
                            LineNewNo++;
                        }
                    }
                    _context.tblVConfirmRooms.AddRange(NewVendConfRoomList);
                    var AllVendConfRoomList = new List<tblVConfirmRoom>();
                    AllVendConfRoomList.AddRange(VConfRommUpd);
                    AllVendConfRoomList.AddRange(NewVendConfRoomList);
                    UpdateVendorConfirmDetail(Data.VendorID, Data.GroupID, Data.ArrivalDate, AllVendConfRoomList);

                    _context.SaveChanges();
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    Error.Message = ex.Message;
                    logger.Error(ex.ToMessageAndCompleteStacktrace());
                    transaction.Rollback();
                }
            }
            var VConfRoom = _context.tblVConfirmRooms.AsQueryable();
            VConfRoom = VConfRoom.Where(vroom => vroom.GroupID == Data.GroupID && vroom.VendorID == Data.VendorID);
            var VConf = _context.tblVendorConfirms.AsQueryable();
            VConf = VConf.Where(vconf => vconf.GroupID == Data.GroupID && vconf.VendorID == Data.VendorID);
            var GroupBData = InitOperationGroupVendorGridBData(VConfRoom, VConf);
            GroupBData.Error = Error;
            return GroupBData;
        }
        public OperationGVendorRoomGridBData RemoveOperationGroupVendorRooms(int GroupID, int VendorID, DateTime ArrivalDate, int LineNo)
        {
            ErrorBInfo Error = new ErrorBInfo();
            using (var transaction = _context.Database.BeginTransaction(IsolationLevel.Serializable))
            {
                try
                {
                    var RoomConfDel = _context.tblVConfirmRooms.Where(room => room.GroupID == GroupID && room.VendorID == VendorID && room.ArrivalDate == ArrivalDate && room.LineNo == LineNo).SingleOrDefault();
                    var VndConfRooms = _context.tblVConfirmRooms.Where(room => room.GroupID == GroupID && room.VendorID == VendorID && room.ArrivalDate == ArrivalDate).ToList();

                    if (RoomConfDel != null)
                    {
                        _context.tblVConfirmRooms.Remove(RoomConfDel);
                        VndConfRooms.Remove(RoomConfDel);
                    }
                    UpdateVendorConfirmDetail(VendorID, GroupID, ArrivalDate, VndConfRooms);
                    _context.SaveChanges();
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    Error.errorCode = 4545;
                    Error.Message = ex.Message;
                    transaction.Rollback();
                    logger.Error(ex.ToMessageAndCompleteStacktrace());
                }
            }
            var VConfRoom = _context.tblVConfirmRooms.AsQueryable();
            VConfRoom = VConfRoom.Where(vroom => vroom.GroupID == GroupID && vroom.VendorID == VendorID);
            var VConf = _context.tblVendorConfirms.AsQueryable();
            VConf = VConf.Where(vconf => vconf.GroupID == GroupID && vconf.VendorID == VendorID);
            var GroupBData = InitOperationGroupVendorGridBData(VConfRoom, VConf);
            GroupBData.Error = Error;
            return GroupBData;
        }
        public OperationAttrBusConfirmGridBData OperationAttrBusConfirmGridLoad(int GroupID, int VendorID, DateTime ArrivalDate, string VendorType)
        {
            IQueryable<tblAttractionsConfirm> AttrConfirm = _context.tblAttractionsConfirms.AsQueryable();
            IQueryable<tblRestaurantsConfirm> RestConfirm = _context.tblRestaurantsConfirms.AsQueryable();
            IQueryable<tblBusConfirm> BusConfirm = _context.tblBusConfirms.AsQueryable();
            IQueryable<tblMiscConfirm> MiscConfirm = _context.tblMiscConfirms.AsQueryable();
            switch (VendorType)
            {
                case "Bus":
                    {
                        BusConfirm = BusConfirm.Where(bconf => bconf.GroupID == GroupID && bconf.VendorID == VendorID && bconf.StartDate == ArrivalDate);
                        return InitOperationBusConfirmBData(BusConfirm);
                    }
                case "Restaurants":
                    {
                        RestConfirm = RestConfirm.Where(rconf => rconf.GroupID == GroupID && rconf.VendorID == VendorID && rconf.StartDate == ArrivalDate);
                        return InitOperationRestaurantsConfirmBData(RestConfirm);
                    }
                case "Attractions":
                    {
                        AttrConfirm = AttrConfirm.Where(aconf => aconf.GroupID == GroupID && aconf.VendorID == VendorID && aconf.StartDate == ArrivalDate);
                        return InitOperationAttractionsConfirmBData(AttrConfirm);
                    }
                case "Misc":
                    {
                        MiscConfirm = MiscConfirm.Where(mconf => mconf.GroupID == GroupID && mconf.VendorID == VendorID && mconf.StartDate == ArrivalDate);
                        return InitOperationMiscConfirmBData(MiscConfirm);
                    }
                default:
                    {
                        OperationAttrBusConfirmGridBData AttrBusConfData = new OperationAttrBusConfirmGridBData();
                        AttrBusConfData.Status = new Dictionary<int, string>();
                        AttrBusConfData.Service = new Dictionary<int, string>();
                        return AttrBusConfData;
                    }
            }
        }
        public OperationVendorConfirmGridBData OperationVendorConfirmGridLoad(int GroupID, int VendorID, DateTime ArrivalDate)
        {
            IQueryable<tblVendorConfirm> VendConfirm = _context.tblVendorConfirms.AsQueryable();
            VendConfirm = VendConfirm.Where(vconf => vconf.GroupID == GroupID && vconf.VendorID == VendorID && vconf.ArrivalDate == ArrivalDate);
            IQueryable<tblVConfirmDetail> VendConfirmDet = _context.tblVConfirmDetails.AsQueryable();
            VendConfirmDet = VendConfirmDet.Where(vconfDet => vconfDet.GroupID == GroupID && vconfDet.VendorID == VendorID && vconfDet.ArrivalDate == ArrivalDate);
            return InitOperationVendorConfirmBData(VendConfirm, VendConfirmDet);
        }
        public OperationAttrBusConfirmGridBData SaveOperationAttrBusConfirm(OperationAttrBusConfirmGridBData Data)
        {
            ErrorBInfo Error = new ErrorBInfo();
            switch (Data.VendorType)
            {
                case "Bus":
                    {
                        using (var transaction = _context.Database.BeginTransaction(IsolationLevel.Serializable))
                        {
                            try
                            {
                                var group = _context.tblGroups.Where(grp => grp.GroupID == Data.GroupID).SingleOrDefault();
                                if (group != null)
                                    group.TechProgUpdt = true;

                                var BusConf = _context.tblBusConfirms.Where(Bc => Bc.GroupID == Data.GroupID && Bc.VendorID == Data.VendorID && Bc.StartDate == Data.ArrivalDate).SingleOrDefault();
                                if (BusConf != null)
                                {
                                    BusConf.StatusID = Data.StatusID;
                                    BusConf.Notes = Data.Note;
                                    BusConf.Time = Data.ArrivalTime;
                                }
                                _context.SaveChanges();
                                transaction.Commit();
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                Error.errorCode = 6767;
                                Error.Message = ex.Message;
                                logger.Error(ex.ToMessageAndCompleteStacktrace());
                            }
                        }
                        IQueryable<tblBusConfirm> BusConfirm = _context.tblBusConfirms.AsQueryable();
                        BusConfirm = BusConfirm.Where(bconf => bconf.GroupID == Data.GroupID && bconf.VendorID == Data.VendorID && bconf.StartDate == Data.ArrivalDate);
                        var BusConfBdata = InitOperationBusConfirmBData(BusConfirm);
                        BusConfBdata.Error = Error;
                        return BusConfBdata;
                    }
                case "Attractions":
                    {
                        using (var transaction = _context.Database.BeginTransaction(IsolationLevel.Serializable))
                        {
                            try
                            {
                                var group = _context.tblGroups.Where(grp => grp.GroupID == Data.GroupID).SingleOrDefault();
                                if (group != null)
                                    group.TechProgUpdt = true;

                                var AttractionsConf = _context.tblAttractionsConfirms.Where(Ac => Ac.GroupID == Data.GroupID && Ac.VendorID == Data.VendorID && Ac.StartDate == Data.ArrivalDate).SingleOrDefault();
                                if (AttractionsConf != null)
                                {
                                    AttractionsConf.StatusID = Data.StatusID;
                                    AttractionsConf.Notes = Data.Note;
                                    AttractionsConf.Time = Data.ArrivalTime;
                                }
                                _context.SaveChanges();
                                transaction.Commit();
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                Error.errorCode = 6767;
                                Error.Message = ex.Message;
                                logger.Error(ex.ToMessageAndCompleteStacktrace());
                            }
                        }
                        IQueryable<tblAttractionsConfirm> AttractionsConfirm = _context.tblAttractionsConfirms.AsQueryable();
                        AttractionsConfirm = AttractionsConfirm.Where(aconf => aconf.GroupID == Data.GroupID && aconf.VendorID == Data.VendorID && aconf.StartDate == Data.ArrivalDate);
                        var AttractionsConfBdata = InitOperationAttractionsConfirmBData(AttractionsConfirm);
                        AttractionsConfBdata.Error = Error;
                        return AttractionsConfBdata;
                    }
                case "Restaurants":
                    {
                        using (var transaction = _context.Database.BeginTransaction(IsolationLevel.Serializable))
                        {
                            try
                            {
                                var group = _context.tblGroups.Where(grp => grp.GroupID == Data.GroupID).SingleOrDefault();
                                if (group != null)
                                    group.TechProgUpdt = true;

                                var RestaurantsConf = _context.tblRestaurantsConfirms.Where(Rc => Rc.GroupID == Data.GroupID && Rc.VendorID == Data.VendorID && Rc.StartDate == Data.ArrivalDate).SingleOrDefault();
                                if (RestaurantsConf != null)
                                {
                                    RestaurantsConf.StatusID = Data.StatusID;
                                    RestaurantsConf.Notes = Data.Note;
                                    RestaurantsConf.Time = Data.ArrivalTime;
                                }
                                _context.SaveChanges();
                                transaction.Commit();
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                Error.errorCode = 6767;
                                Error.Message = ex.Message;
                                logger.Error(ex.ToMessageAndCompleteStacktrace());
                            }
                        }
                        IQueryable<tblRestaurantsConfirm> RestaurantsConfirm = _context.tblRestaurantsConfirms.AsQueryable();
                        RestaurantsConfirm = RestaurantsConfirm.Where(aconf => aconf.GroupID == Data.GroupID && aconf.VendorID == Data.VendorID && aconf.StartDate == Data.ArrivalDate);
                        var RestaurantsConfBdata = InitOperationRestaurantsConfirmBData(RestaurantsConfirm);
                        RestaurantsConfBdata.Error = Error;
                        return RestaurantsConfBdata;
                    }
                default:
                    {
                        using (var transaction = _context.Database.BeginTransaction(IsolationLevel.Serializable))
                        {
                            try
                            {
                                var group = _context.tblGroups.Where(grp => grp.GroupID == Data.GroupID).SingleOrDefault();
                                if (group != null)
                                    group.TechProgUpdt = true;

                                var BusConf = _context.tblBusConfirms.Where(Bc => Bc.GroupID == Data.GroupID && Bc.VendorID == Data.VendorID && Bc.StartDate == Data.ArrivalDate).SingleOrDefault();
                                if (BusConf != null)
                                {
                                    BusConf.StatusID = Data.StatusID;
                                    BusConf.Notes = Data.Note;
                                    BusConf.Time = Data.ArrivalTime;
                                }
                                _context.SaveChanges();
                                transaction.Commit();
                            }
                            catch (Exception ex)
                            {
                                transaction.Rollback();
                                Error.errorCode = 6767;
                                Error.Message = ex.Message;
                                logger.Error(ex.ToMessageAndCompleteStacktrace());
                            }
                        }
                        IQueryable<tblBusConfirm> BusConfirm = _context.tblBusConfirms.AsQueryable();
                        BusConfirm = BusConfirm.Where(bconf => bconf.GroupID == Data.GroupID && bconf.VendorID == Data.VendorID && bconf.StartDate == Data.ArrivalDate);
                        var BusConfBdata = InitOperationBusConfirmBData(BusConfirm);
                        BusConfBdata.Error = Error;
                        return BusConfBdata;
                    }
            }
        }
        public OperationVendorConfirmGridBData SaveOperationVendorConfirm(OperationVendorConfirmGridBData Data)
        {
            ErrorBInfo Error = new ErrorBInfo();
            using (var transaction = _context.Database.BeginTransaction(IsolationLevel.Serializable))
            {
                try
                {
                    int LineNo = 1;
                    if (_context.tblVendorConfirms.Any(vcd => vcd.GroupID == Data.GroupID && vcd.VendorID == Data.VendorID && vcd.ArrivalDate == Data.ArrivalDate))
                        LineNo = _context.tblVConfirmDetails.Where(vcd => vcd.GroupID == Data.GroupID && vcd.VendorID == Data.VendorID && vcd.ArrivalDate == Data.ArrivalDate).Max(vcd => vcd.LineNo) + 1;
                    var ChangeVendConfDet = _context.tblVConfirmDetails.Where(vcd => vcd.GroupID == Data.GroupID && vcd.VendorID == Data.VendorID && vcd.ArrivalDate == Data.ArrivalDate).ToList();
                    var group = _context.tblGroups.Where(grp => grp.GroupID == Data.GroupID).SingleOrDefault();
                    if (group != null)
                        group.TechProgUpdt = true;
                    
                    foreach (var row in Data.Rows)
                    {
                        if(row.Description == "Single" && row.SelServiceID == null)
                        {
                            var SingleConfDet = ChangeVendConfDet.Where(vcd => vcd.StartDate == row.StartDate && vcd.EndDate == row.EndDate && vcd.ServiceID == 1 && vcd.Description == null && vcd.ManualFlg != true).FirstOrDefault();
                            if(SingleConfDet != null)
                            {
                                SingleConfDet.Price = row.Price;
                                SingleConfDet.Qty = row.Qty;
                            }
                        }
                        if (row.Description == "Double" && row.SelServiceID == null)
                        {
                            var DoubleConfDet = ChangeVendConfDet.Where(vcd => vcd.StartDate == row.StartDate && vcd.EndDate == row.EndDate && vcd.ServiceID == 2 && vcd.Description == null && vcd.ManualFlg != true).FirstOrDefault();
                            if (DoubleConfDet != null)
                            {
                                DoubleConfDet.Price = row.Price;
                                DoubleConfDet.Qty = row.Qty;
                            }
                        }
                        if (row.Description == "Twin" && row.SelServiceID == null)
                        {
                            var TwinConfDet = ChangeVendConfDet.Where(vcd => vcd.StartDate == row.StartDate && vcd.EndDate == row.EndDate && vcd.ServiceID == 3 && vcd.Description == null && vcd.ManualFlg != true).FirstOrDefault();
                            if (TwinConfDet != null)
                            {
                                TwinConfDet.Price = row.Price;
                                TwinConfDet.Qty = row.Qty;
                            }
                        }
                        if (row.Description == "Triple" && row.SelServiceID == null)
                        {
                            var TripleConfDet = ChangeVendConfDet.Where(vcd => vcd.StartDate == row.StartDate && vcd.EndDate == row.EndDate && vcd.ServiceID == 4 && vcd.Description == null && vcd.ManualFlg != true).FirstOrDefault();
                            if (TripleConfDet != null)
                            {
                                TripleConfDet.Price = row.Price;
                                TripleConfDet.Qty = row.Qty;
                            }
                        }
                        if (row.Description == "Quad" && row.SelServiceID == null)
                        {
                            var QuadConfDet = ChangeVendConfDet.Where(vcd => vcd.StartDate == row.StartDate && vcd.EndDate == row.EndDate && vcd.ServiceID == 5 && vcd.Description == null && vcd.ManualFlg != true).FirstOrDefault();
                            if (QuadConfDet != null)
                            {
                                QuadConfDet.Price = row.Price;
                                QuadConfDet.Qty = row.Qty;
                            }
                        }
                        if (row.Description == "Driver" && row.SelServiceID == null)
                        {
                            var DriverConfDet = ChangeVendConfDet.Where(vcd => vcd.StartDate == row.StartDate && vcd.EndDate == row.EndDate && vcd.ServiceID == 79 && vcd.Description == null && vcd.ManualFlg != true).FirstOrDefault();
                            if (DriverConfDet != null)
                            {
                                DriverConfDet.Price = row.Price;
                                DriverConfDet.Qty = row.Qty;
                            }
                        }
                        if (row.Description == "Guide" && row.SelServiceID == null)
                        {
                            var GuideConfDet = ChangeVendConfDet.Where(vcd => vcd.StartDate == row.StartDate && vcd.EndDate == row.EndDate && vcd.ServiceID == 87 && vcd.Description == null && vcd.ManualFlg != true).FirstOrDefault();
                            if (GuideConfDet != null)
                            {
                                GuideConfDet.Price = row.Price;
                                GuideConfDet.Qty = row.Qty;
                            }
                        }
                        if (row.Description == "ABF" && row.SelServiceID == null)
                        {
                            var ABFConfDet = ChangeVendConfDet.Where(vcd => vcd.StartDate == row.StartDate && vcd.EndDate == row.EndDate && vcd.ServiceID == 6 && vcd.Description == null && vcd.ManualFlg != true).FirstOrDefault();
                            if (ABFConfDet != null)
                            {
                                ABFConfDet.Price = row.Price;
                                ABFConfDet.Qty = row.Qty;
                                ABFConfDet.ProductID = row.Product;
                            }
                        }
                        if (row.Description == "CBF" && row.SelServiceID == null)
                        {
                            var CBFConfDet = ChangeVendConfDet.Where(vcd => vcd.StartDate == row.StartDate && vcd.EndDate == row.EndDate && vcd.ServiceID == 7 && vcd.Description == null && vcd.ManualFlg != true).FirstOrDefault();
                            if (CBFConfDet != null)
                            {
                                CBFConfDet.Price = row.Price;
                                CBFConfDet.Qty = row.Qty;
                                CBFConfDet.ProductID = row.Product;
                            }
                        }
                        if (row.Description == "Lunch" && row.SelServiceID == null)
                        {
                            var LunchConfDet = ChangeVendConfDet.Where(vcd => vcd.StartDate == row.StartDate && vcd.EndDate == row.EndDate && vcd.ServiceID == 70 && vcd.Description == null && vcd.ManualFlg != true).FirstOrDefault();
                            if (LunchConfDet != null)
                            {
                                LunchConfDet.Price = row.Price;
                                LunchConfDet.Qty = row.Qty;
                                LunchConfDet.ProductID = row.Product;
                            }
                        }
                        if (row.Description == "Dinner" && row.SelServiceID == null)
                        {
                            var DinnerConfDet = ChangeVendConfDet.Where(vcd => vcd.StartDate == row.StartDate && vcd.EndDate == row.EndDate && vcd.ServiceID == 71 && vcd.Description == null && vcd.ManualFlg != true).FirstOrDefault();
                            if (DinnerConfDet != null)
                            {
                                DinnerConfDet.Price = row.Price;
                                DinnerConfDet.Qty = row.Qty;
                                DinnerConfDet.ProductID = row.Product;
                            }
                        }
                        if (row.Description == "Baggage" && row.SelServiceID == null)
                        {
                            var BaggageConfDet = ChangeVendConfDet.Where(vcd => vcd.StartDate == row.StartDate && vcd.EndDate == row.EndDate && vcd.ServiceID == 103 && vcd.Description == null && vcd.ManualFlg != true).FirstOrDefault();
                            if (BaggageConfDet != null)
                            {
                                BaggageConfDet.Price = row.Price;
                                BaggageConfDet.Qty = row.Qty;
                            }
                        }
                        if(row.IsRow == true)
                        {
                            var ManualDet = ChangeVendConfDet.Where(vcd => vcd.LineNo == row.LineNo).SingleOrDefault();
                            if(ManualDet != null)
                            {
                                ManualDet.StartDate = row.StartDate;
                                ManualDet.EndDate = row.EndDate;
                                ManualDet.Description = row.Description;
                                ManualDet.Price = row.Price;
                                ManualDet.Qty = row.Qty;
                                ManualDet.XQty = row.XQty;
                                ManualDet.ServiceID = row.SelServiceID;
                            }
                            else
                            {
                                // new extra service
                                tblVConfirmDetail VcDet = new tblVConfirmDetail
                                {
                                    LineNo = LineNo,
                                    GroupID = Data.GroupID,
                                    VendorID = Data.VendorID,
                                    ArrivalDate = Data.ArrivalDate,
                                    StartDate = row.StartDate,
                                    EndDate = row.EndDate,
                                    Price = row.Price,
                                    Qty = row.Qty,
                                    XQty = row.XQty,
                                    Description = row.Description,
                                    ServiceID = row.SelServiceID,
                                    ManualFlg = true,
                                };
                                LineNo++;
                                _context.tblVConfirmDetails.Add(VcDet);
                            }
                        }                       
                    }
                    var VendConf = _context.tblVendorConfirms.Where(Vc => Vc.GroupID == Data.GroupID && Vc.VendorID == Data.VendorID && Vc.ArrivalDate == Data.ArrivalDate).SingleOrDefault();
                    if (VendConf != null)
                    {
                        VendConf.StatusID = Data.StatusID;
                        VendConf.Tax = Data.Tax;
                        VendConf.OccTax = Data.OccTax;
                        VendConf.Luggage = Data.Luggage;
                        VendConf.ConfirmedBy = Data.ConfirmedBy;
                        VendConf.ConfirmDate = Data.ConfirmDate;
                        VendConf.Notes = Data.Note;
                        VendConf.DateIssued = Data.IssueDate;
                        VendConf.ArrivalTime = Data.ArrivalTime;
                        VendConf.DepartureDate = Data.DepartureDate;
                        VendConf.DepartureTime = Data.DepartureTime;

                        // Check if all Abf, Cfb, etc. unchecked uncheck from hotel also
                        if (!Data.Rows.Any(row => row.Description == "ABF" && row.SelServiceID == null && row.Product == 1))
                            VendConf.ABFChecked = false;
                        if (!Data.Rows.Any(row => row.Description == "CBF" && row.SelServiceID == null && row.Product == 1))
                            VendConf.CBFChecked = false;
                        if (!Data.Rows.Any(row => row.Description == "Lunch" && row.SelServiceID == null && row.Product == 1))
                            VendConf.LunchChecked = false;
                        if (!Data.Rows.Any(row => row.Description == "Dinner" && row.SelServiceID == null && row.Product == 1))
                            VendConf.DinnerChecked = false;
                    }
                    _context.SaveChanges();
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    Error.errorCode = 6767;
                    Error.Message = ex.Message;
                    logger.Error(ex.ToMessageAndCompleteStacktrace());
                }
            }
            IQueryable<tblVendorConfirm> VendConfirm = _context.tblVendorConfirms.AsQueryable();
            VendConfirm = VendConfirm.Where(vconf => vconf.GroupID == Data.GroupID && vconf.VendorID == Data.VendorID && vconf.ArrivalDate == Data.ArrivalDate);
            IQueryable<tblVConfirmDetail> VendConfirmDet = _context.tblVConfirmDetails.AsQueryable();
            VendConfirmDet = VendConfirmDet.Where(vconfDet => vconfDet.GroupID == Data.GroupID && vconfDet.VendorID == Data.VendorID && vconfDet.ArrivalDate == Data.ArrivalDate);
            var VendConfBdata = InitOperationVendorConfirmBData(VendConfirm, VendConfirmDet);
            VendConfBdata.Error = Error;
            return VendConfBdata;
        }
        public ErrorBInfo OperationVendorConfirmUpdateProvide(int GroupID, int VendorID, DateTime ArrivalDate)
        {
            ErrorBInfo Error = new ErrorBInfo();
            List<int> MealList = new List<int> { 6, 7, 70, 71 };
            try
            {
                var VendConfDet = _context.tblVConfirmDetails.Where(VcDet => VcDet.GroupID == GroupID && VcDet.VendorID == VendorID && VcDet.ArrivalDate == ArrivalDate && MealList.Contains((int)VcDet.ServiceID)).ToList();
                var VendConfDetABF = VendConfDet.Where(VcDet => VcDet.ServiceID == 6).ToList();
                var VendConfDetCBF = VendConfDet.Where(VcDet => VcDet.ServiceID == 7).ToList();
                var VendConfDetLunch = VendConfDet.Where(VcDet => VcDet.ServiceID == 70).ToList();
                var VendConfDetDinner = VendConfDet.Where(VcDet => VcDet.ServiceID == 71).ToList();
                StringBuilder Str = new StringBuilder();
                string Provide = "";
                int ind = 0;
                // ABF
                foreach (var itm in VendConfDetABF)
                {
                    if(itm.ProductID == 1)
                    {
                        if(Str.ToString().Contains(Convert.ToDateTime(itm.StartDate).ToString("MMM")))
                        {
                            if(VendConfDetABF.Count > ind)
                                Str.Append(Convert.ToDateTime(itm.StartDate).ToString("dd") + ", ");
                            else
                                Str.Append(Convert.ToDateTime(itm.StartDate).ToString("dd"));
                        }
                        else
                        {
                            if(VendConfDetABF.Count > ind)
                                Str.Append(Convert.ToDateTime(itm.StartDate).ToString("MMM dd") + ", ");
                            else
                                Str.Append(Convert.ToDateTime(itm.StartDate).ToString("MMM dd"));
                        }
                    } 
                    ind++;
                }
                if (Str.Length > 0)
                    Provide = "American Breakfast: " + Str.ToString() + "\n";
                // CBF
                ind = 0;
                Str = new StringBuilder();
                foreach (var itm in VendConfDetCBF)
                {
                    if (itm.ProductID == 1)
                    {
                        if (Str.ToString().Contains(Convert.ToDateTime(itm.StartDate).ToString("MMM")))
                        {
                            if (VendConfDetCBF.Count > ind)
                                Str.Append(Convert.ToDateTime(itm.StartDate).ToString("dd") + ", ");
                            else
                                Str.Append(Convert.ToDateTime(itm.StartDate).ToString("dd"));
                        }
                        else
                        {
                            if (VendConfDetCBF.Count > ind)
                                Str.Append(Convert.ToDateTime(itm.StartDate).ToString("MMM dd") + ", ");
                            else
                                Str.Append(Convert.ToDateTime(itm.StartDate).ToString("MMM dd"));
                        }
                    }
                    ind++;
                }
                if (Str.Length > 0)
                    Provide = Provide + "Continental Breakfast: " + Str.ToString() + "\n";
                // Lunch
                ind = 0;
                Str = new StringBuilder();
                foreach (var itm in VendConfDetLunch)
                {
                    if (itm.ProductID == 1)
                    {
                        if (Str.ToString().Contains(Convert.ToDateTime(itm.StartDate).ToString("MMM")))
                        {
                            if (VendConfDetLunch.Count > ind)
                                Str.Append(Convert.ToDateTime(itm.StartDate).ToString("dd") + ", ");
                            else
                                Str.Append(Convert.ToDateTime(itm.StartDate).ToString("dd"));
                        }
                        else
                        {
                            if (VendConfDetLunch.Count > ind)
                                Str.Append(Convert.ToDateTime(itm.StartDate).ToString("MMM dd") + ", ");
                            else
                                Str.Append(Convert.ToDateTime(itm.StartDate).ToString("MMM dd"));
                        }
                    }
                    ind++;
                }
                if (Str.Length > 0)
                    Provide = Provide + "Lunch: " + Str.ToString() + "\n";
                // Dinner
                ind = 0;
                Str = new StringBuilder();
                foreach (var itm in VendConfDetDinner)
                {
                    if (itm.ProductID == 1)
                    {
                        if (Str.ToString().Contains(Convert.ToDateTime(itm.StartDate).ToString("MMM")))
                        {
                            if (VendConfDetDinner.Count > ind)
                                Str.Append(Convert.ToDateTime(itm.StartDate).ToString("dd") + ", ");
                            else
                                Str.Append(Convert.ToDateTime(itm.StartDate).ToString("dd"));
                        }
                        else
                        {
                            if (VendConfDetDinner.Count > ind)
                                Str.Append(Convert.ToDateTime(itm.StartDate).ToString("MMM dd") + ", ");
                            else
                                Str.Append(Convert.ToDateTime(itm.StartDate).ToString("MMM dd"));
                        }
                    }
                    ind++;
                }
                if (Str.Length > 0)
                    Provide = Provide + "Dinner: " + Str.ToString() + "\n";

                // VendConf
                var VendConf = _context.tblVendorConfirms.Where(VConf => VConf.GroupID == GroupID && VConf.VendorID == VendorID && VConf.ArrivalDate == ArrivalDate).SingleOrDefault();
                if (VendConf != null)
                {
                    VendConf.RoomListNotes = Provide;
                    _context.SaveChanges();
                }     
            }
            catch (Exception ex)
            {
                Error.errorCode = 23232;
                Error.Message = ex.Message;
            }
            return Error;
        }
        public ErrorBInfo UpdateVendorConfirmPath(int VendorID, int GroupID, string VendorConfirmPath, string VendorType, bool UpdateAll)
        {
            ErrorBInfo Error = new ErrorBInfo();
            switch (VendorType)
            {
                case "Hotel":
                    {
                        var SaveEntityVendorConfirm = _context.tblVendorConfirms.Where(vcnf => vcnf.VendorID == VendorID && vcnf.GroupID == GroupID).FirstOrDefault();
                        if (SaveEntityVendorConfirm != null)
                        {
                            try
                            {
                                SaveEntityVendorConfirm.VendorConfirmFile = VendorConfirmPath;
                                _context.SaveChanges();
                            }
                            catch (Exception ex)
                            {
                                Error.errorCode = 2323;
                                Error.Message = ex.Message;
                                logger.Error(ex.ToMessageAndCompleteStacktrace());
                            }
                        }
                        return Error;
                    }
                case "Bus":
                    {
                        if (UpdateAll)
                        {
                            var SaveEntityBusConfirmList = _context.tblBusConfirms.Where(bcnf => bcnf.VendorID == VendorID && bcnf.GroupID == GroupID).ToList();
                            if (SaveEntityBusConfirmList != null && SaveEntityBusConfirmList.Count > 0)
                            {
                                try
                                {
                                    foreach (var BusConfirm in SaveEntityBusConfirmList)
                                    {
                                        BusConfirm.BusConfirmFile = VendorConfirmPath;
                                    }
                                    _context.SaveChanges();
                                }
                                catch (Exception ex)
                                {
                                    Error.errorCode = 2323;
                                    Error.Message = ex.Message;
                                    logger.Error(ex.ToMessageAndCompleteStacktrace());
                                }
                            }
                        }
                        else
                        {
                            var SaveEntityBusConfirm = _context.tblBusConfirms.Where(bcnf => bcnf.VendorID == VendorID && bcnf.GroupID == GroupID).FirstOrDefault();
                            if (SaveEntityBusConfirm != null)
                            {
                                try
                                {
                                    SaveEntityBusConfirm.BusConfirmFile = VendorConfirmPath;
                                    _context.SaveChanges();
                                }
                                catch (Exception ex)
                                {
                                    Error.errorCode = 2323;
                                    Error.Message = ex.Message;
                                    logger.Error(ex.ToMessageAndCompleteStacktrace());
                                }
                            }
                        }
                        return Error;
                    }
                case "Attractions":
                    {
                        if (UpdateAll)
                        {
                            var SaveEntityAttractionsConfirmList = _context.tblAttractionsConfirms.Where(acnf => acnf.VendorID == VendorID && acnf.GroupID == GroupID).ToList();
                            if (SaveEntityAttractionsConfirmList != null && SaveEntityAttractionsConfirmList.Count > 0)
                            {
                                try
                                {
                                    foreach (var AttractionsConfirm in SaveEntityAttractionsConfirmList)
                                    {
                                        AttractionsConfirm.AttractionsConfirmFile = VendorConfirmPath;
                                    }
                                    _context.SaveChanges();
                                }
                                catch (Exception ex)
                                {
                                    Error.errorCode = 2323;
                                    Error.Message = ex.Message;
                                    logger.Error(ex.ToMessageAndCompleteStacktrace());
                                }
                            }
                        }
                        else
                        {
                            var SaveEntityAttractionsConfirm = _context.tblAttractionsConfirms.Where(acnf => acnf.VendorID == VendorID && acnf.GroupID == GroupID).FirstOrDefault();
                            if (SaveEntityAttractionsConfirm != null)
                            {
                                try
                                {
                                    SaveEntityAttractionsConfirm.AttractionsConfirmFile = VendorConfirmPath;
                                    _context.SaveChanges();
                                }
                                catch (Exception ex)
                                {
                                    Error.errorCode = 2323;
                                    Error.Message = ex.Message;
                                    logger.Error(ex.ToMessageAndCompleteStacktrace());
                                }
                            }
                        }
                        return Error;
                    }
                case "Restaurants":
                    {
                        if (UpdateAll)
                        {
                            var SaveEntityRestaurantsConfirmList = _context.tblRestaurantsConfirms.Where(rcnf => rcnf.VendorID == VendorID && rcnf.GroupID == GroupID).ToList();
                            if (SaveEntityRestaurantsConfirmList != null && SaveEntityRestaurantsConfirmList.Count > 0)
                            {
                                try
                                {
                                    foreach (var RestaurantsConfirm in SaveEntityRestaurantsConfirmList)
                                    {
                                        RestaurantsConfirm.RestaurantsConfirmFile = VendorConfirmPath;
                                    }
                                    _context.SaveChanges();
                                }
                                catch (Exception ex)
                                {
                                    Error.errorCode = 2323;
                                    Error.Message = ex.Message;
                                    logger.Error(ex.ToMessageAndCompleteStacktrace());
                                }
                            }
                        }
                        else
                        {
                            var SaveEntityRestaurantsConfirm = _context.tblRestaurantsConfirms.Where(rcnf => rcnf.VendorID == VendorID && rcnf.GroupID == GroupID).FirstOrDefault();
                            if (SaveEntityRestaurantsConfirm != null)
                            {
                                try
                                {
                                    SaveEntityRestaurantsConfirm.RestaurantsConfirmFile = VendorConfirmPath;
                                    _context.SaveChanges();
                                }
                                catch (Exception ex)
                                {
                                    Error.errorCode = 2323;
                                    Error.Message = ex.Message;
                                    logger.Error(ex.ToMessageAndCompleteStacktrace());
                                }
                            }
                        }
                        return Error;
                    }
                case "Misc":
                    {
                        if (UpdateAll)
                        {
                            var SaveEntityMiscConfirmList = _context.tblMiscConfirms.Where(mcnf => mcnf.VendorID == VendorID && mcnf.GroupID == GroupID).ToList();
                            if (SaveEntityMiscConfirmList != null && SaveEntityMiscConfirmList.Count > 0)
                            {
                                try
                                {
                                    foreach (var MiscConfirm in SaveEntityMiscConfirmList)
                                    {
                                        MiscConfirm.MiscConfirmFile = VendorConfirmPath;
                                    }
                                    _context.SaveChanges();
                                }
                                catch (Exception ex)
                                {
                                    Error.errorCode = 2323;
                                    Error.Message = ex.Message;
                                    logger.Error(ex.ToMessageAndCompleteStacktrace());
                                }
                            }
                        }
                        else
                        {
                            var SaveEntityMiscConfirm = _context.tblMiscConfirms.Where(mcnf => mcnf.VendorID == VendorID && mcnf.GroupID == GroupID).FirstOrDefault();
                            if (SaveEntityMiscConfirm != null)
                            {
                                try
                                {
                                    SaveEntityMiscConfirm.MiscConfirmFile = VendorConfirmPath;
                                    _context.SaveChanges();
                                }
                                catch (Exception ex)
                                {
                                    Error.errorCode = 2323;
                                    Error.Message = ex.Message;
                                    logger.Error(ex.ToMessageAndCompleteStacktrace());
                                }
                            }
                        }
                        return Error;
                    }
                default:
                    return Error;
            }
        }
        public bool CheckGroupCodeRegion(string GroupCode, List<string> UserRegions)
        {
            var QuotaID = _context.tblGroups.Where(grp => grp.GroupCode == GroupCode).Select(grp => grp.QuotaID).SingleOrDefault();
            if (_context.tblQuotations.Any(quota => quota.QuotaID == QuotaID && UserRegions.Contains(quota.Region)))
                return true;
            return false;
        }
        #region Optional
        public OperationOptionalBData LoadOperationOptional(int VendorID)
        {
            OperationOptionalBData OptionalBData = new OperationOptionalBData();
            OptionalBData.Rows = new List<OperationOptionalDetailsBData>();
            OptionalBData.VendorID = VendorID;
            OptionalBData.Rows = (from opt in _context.tblOptionals
                                  from optdet in _context.tblOptionalDetails
                                  where opt.VendorID == VendorID
                                  && opt.Active == true
                                  && opt.OptionalID == optdet.OptionalID
                                  select new OperationOptionalDetailsBData {
                                      OptionalID = opt.OptionalID,
                                      ContractStartDate = opt.ContractStartDate,
                                      ContractEndDate = opt.ContractEndDate,
                                      OptionalDetailID = optdet.OptionalDetailID,
                                      PaxFrom = optdet.PaxFrom,
                                      PaxTo = optdet.PaxTo,
                                      Price = optdet.Price,
                                      SelectedCurrency = optdet.Currency,
                                      BusIncluded = optdet.BusIncluded,
                                      GuideIncluded = optdet.GuideIncluded,
                                  }).ToList();
            if (OptionalBData.Rows == null)
            {
                OptionalBData.Rows = new List<OperationOptionalDetailsBData>();
            }
            return OptionalBData;
        }
        #endregion
        #region Invoice
        public OperationInvoiceBData OperationLoadInvoiceByGroupID(int GroupID)
        {
            IQueryable<tblGroupInvoice> GroupInv = _context.tblGroupInvoices.AsQueryable();
            GroupInv = GroupInv.Where(Inv => Inv.GroupID == GroupID);
            return InitOperationInvoiceBData(GroupInv, GroupID);
        }
        public OperationInvoiceBData OperationLoadGirInvoice(int GroupID, int CustomerID)
        {
            IQueryable<tblGirGroupInvoice> GirInv = _context.tblGirGroupInvoices.AsQueryable();
            GirInv = GirInv.Where(Inv => Inv.GroupID == GroupID && Inv.CustomerID == CustomerID);
            return InitOperationGirInvoiceBData(GirInv, GroupID, CustomerID);
        }
        public OperationInvoiceBData OperationRemoveInvoice(int GroupID, int LineNo, bool IsGir, int CustomerID)
        {
            ErrorBInfo Error = new ErrorBInfo();
            try
            {
                if (IsGir == false)
                {
                    var DelInvoice = _context.tblGroupInvoices.Where(inv => inv.GroupID == GroupID && inv.LineNo == LineNo).SingleOrDefault();
                    if (DelInvoice != null)
                    {
                        _context.tblGroupInvoices.Remove(DelInvoice);
                        _context.SaveChanges();
                    }
                }
                if (IsGir == true)
                {
                    var DelInvoice = _context.tblGirGroupInvoices.Where(inv => inv.GroupID == GroupID && inv.CustomerID == CustomerID && inv.LineNo == LineNo).SingleOrDefault();
                    if (DelInvoice != null)
                    {
                        _context.tblGirGroupInvoices.Remove(DelInvoice);
                        _context.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                Error.errorCode = 1234;
                Error.Message = ex.Message;
                logger.Error(ex.ToMessageAndCompleteStacktrace());
            }
            OperationInvoiceBData InvData = null;
            if (IsGir == false)
            {
                IQueryable<tblGroupInvoice> GroupInv = _context.tblGroupInvoices.AsQueryable();
                GroupInv = GroupInv.Where(Inv => Inv.GroupID == GroupID);
                InvData = InitOperationInvoiceBData(GroupInv, GroupID);
                InvData.Error = Error;
            }
            if (IsGir == true)
            {
                IQueryable<tblGirGroupInvoice> GirInv = _context.tblGirGroupInvoices.AsQueryable();
                GirInv = GirInv.Where(Inv => Inv.GroupID == GroupID && Inv.CustomerID == CustomerID);
                InvData = InitOperationGirInvoiceBData(GirInv, GroupID, CustomerID);
                InvData.Error = Error;
            }
            return InvData;
        }
        public OperationInvoiceBData SaveOperationInvoice(OperationInvoiceBData Data)
        {
            ErrorBInfo Error = new ErrorBInfo();
            var Group = _context.tblGroups.Where(gr => gr.GroupID == Data.InvoiceGroupID).SingleOrDefault();
            using (var transaction = _context.Database.BeginTransaction(IsolationLevel.Serializable))
            {
                try
                {
                    if (Group != null && Group.IsGir == false)
                    {
                        // non gir group Invoices
                        Group.InvComm = Data.InvoiceComment;
                        Group.ProComm = Data.PerformaComment;
                        Group.BankID = Data.SelectedInvBank;
                        Group.PayTerms = Data.SelectedInvPaymentTerms;
                        Group.ProInv = Data.InvProforma;
                        Group.InvDate = Data.InvoiceDate;
                        Group.InvEmployeeID = Data.SelectedInvSalesPerson;
                        Group.CCID = Data.SelectedContactPerson;
                        Group.DepositDue = Data.DepositDue;
                        Group.FinalPayment = Data.FinalPayment;
                        if (Group.UsdCadRate != Data.InvCadUsdRate)
                            Group.RateChangeDate = DateTime.Now;
                        bool CurrChanged = Group.UsdCadRate != Data.InvCadUsdRate;
                        Group.UsdCadRate = Data.InvCadUsdRate;
                        Group.DepositM = Data.DepositM;
                        Group.DepositAmt = Data.DepositAmount;

                        var LineNoes = Data.Rows.Select(row => row.LineNo).ToList();
                        var ChangeInvoices = _context.tblGroupInvoices.Where(inv => LineNoes.Contains(inv.LineNo) && inv.GroupID == Data.InvoiceGroupID).ToList();
                        foreach (var Inv in ChangeInvoices)
                        {
                            var Row = Data.Rows.Where(row => row.LineNo == Inv.LineNo).SingleOrDefault();
                            //var ChPrice = Convert.ToDecimal(Row.Price * Convert.ToDecimal(Data.InvCadUsdRate));
                            if (Row != null)
                            {
                                Inv.Price = Row.Price;
                                Inv.PriceChange = (CurrChanged == true && Row.Currency == "CAD" && Data.InvCadUsdRate != null && Data.InvCadUsdRate > 0) ? Convert.ToDecimal(Data.InvCadUsdRate) * Row.Price : Row.PriceChange;
                                Inv.Quantity = Row.Qty;
                                Inv.Description = Row.Description;
                                Inv.DebCre = Row.CrDeb;
                                Inv.Currency = Row.Currency;
                                Inv.Credit = (CurrChanged == true && Row.Currency == "CAD" && Data.InvCadUsdRate != null && Data.InvCadUsdRate > 0) ? Convert.ToDecimal(Data.InvCadUsdRate) * Row.Credit : Row.Credit;
                                Inv.Debit = (CurrChanged == true && Row.Currency == "CAD" && Data.InvCadUsdRate != null && Data.InvCadUsdRate > 0) ? Convert.ToDecimal(Data.InvCadUsdRate) * Row.Debit : Row.Debit;
                            }
                        }
                        var NewRows = Data.Rows.Where(row => row.LineNo == 0 && row.Price != 0).ToList();
                        int LineNo = 0;
                        // new non gir group Invoices
                        LineNo = _context.tblGroupInvoices.Any(inv => inv.GroupID == Data.InvoiceGroupID) ? _context.tblGroupInvoices.Where(inv => inv.GroupID == Data.InvoiceGroupID).Max(inv => inv.LineNo) : 0;
                        foreach (var Newrow in NewRows)
                        {
                            LineNo++;
                            tblGroupInvoice Invoice = new tblGroupInvoice
                            {
                                Price = Newrow.Price,
                                PriceChange = (CurrChanged == true && Newrow.Currency == "CAD" && Data.InvCadUsdRate != null && Data.InvCadUsdRate > 0) ? Convert.ToDecimal(Data.InvCadUsdRate) * Newrow.Price : Newrow.PriceChange,
                                Quantity = Newrow.Qty,
                                Description = Newrow.Description,
                                DebCre = Newrow.CrDeb,
                                Currency = Newrow.Currency,
                                Credit = (CurrChanged == true && Newrow.Currency == "CAD" && Data.InvCadUsdRate != null && Data.InvCadUsdRate > 0) ? Convert.ToDecimal(Data.InvCadUsdRate) * Newrow.Credit : Newrow.Credit,
                                Debit = (CurrChanged == true && Newrow.Currency == "CAD" && Data.InvCadUsdRate != null && Data.InvCadUsdRate > 0) ? Convert.ToDecimal(Data.InvCadUsdRate) * Newrow.Debit : Newrow.Debit,
                                ItemTypeID = 0,
                                GroupID = Data.InvoiceGroupID,
                                LineNo = LineNo,
                            };
                            _context.tblGroupInvoices.Add(Invoice);
                        }
                    }
                    if (Group != null && Group.IsGir == true)
                    {
                        bool CurrChanged = false;
                        var GirDetails = _context.tblGirGroupDetails.Where(GirDet => GirDet.GroupID == Data.InvoiceGroupID && GirDet.CustomerID == Data.InvoiceCustomerID).SingleOrDefault();
                        if (GirDetails != null)
                        {
                            GirDetails.FinalPayment = Data.FinalPayment;
                            GirDetails.InvComm = Data.InvoiceComment;
                            GirDetails.ProComm = Data.PerformaComment;
                            GirDetails.BankID = Data.SelectedInvBank;
                            GirDetails.PayTerms = Data.SelectedInvPaymentTerms;
                            GirDetails.ProInv = Data.InvProforma;
                            GirDetails.InvDate = Data.InvoiceDate;
                            GirDetails.InvEmployeeID = Data.SelectedInvSalesPerson;
                            GirDetails.CCID = Data.SelectedContactPerson;
                            GirDetails.DepositDue = Data.DepositDue;
                            if (GirDetails.UsdCadRate != Data.InvCadUsdRate)
                                GirDetails.RateChangeDate = DateTime.Now;
                            CurrChanged = GirDetails.UsdCadRate != Data.InvCadUsdRate;
                            GirDetails.UsdCadRate = Data.InvCadUsdRate;
                            GirDetails.DepositM = Data.DepositM;
                            GirDetails.DepositAmt = Data.DepositAmount;
                        }
                        var LineNoes = Data.Rows.Select(row => row.LineNo).ToList();
                        var ChangeGirInvoices = _context.tblGirGroupInvoices.Where(inv => LineNoes.Contains(inv.LineNo) && inv.GroupID == Data.InvoiceGroupID && inv.CustomerID == Data.InvoiceCustomerID).ToList();
                        foreach (var Inv in ChangeGirInvoices)
                        {
                            var Row = Data.Rows.Where(row => row.LineNo == Inv.LineNo).SingleOrDefault();
                            var ChPrice = Convert.ToDecimal(Row.Price * Convert.ToDecimal(Data.InvCadUsdRate));
                            if (Row != null)
                            {
                                Inv.Price = Row.Price;
                                Inv.PriceChange = (CurrChanged == true && Row.Currency == "CAD" && Data.InvCadUsdRate != null && Data.InvCadUsdRate > 0) ? Convert.ToDecimal(Data.InvCadUsdRate) * Row.Price : Row.PriceChange;
                                Inv.Quantity = Row.Qty;
                                Inv.Description = Row.Description;
                                Inv.DebCre = Row.CrDeb;
                                Inv.Currency = Row.Currency;
                                Inv.Credit = (CurrChanged == true && Row.Currency == "CAD" && Data.InvCadUsdRate != null && Data.InvCadUsdRate > 0) ? Convert.ToDecimal(Data.InvCadUsdRate) * Row.Credit : Row.Credit;
                                Inv.Debit = (CurrChanged == true && Row.Currency == "CAD" && Data.InvCadUsdRate != null && Data.InvCadUsdRate > 0) ? Convert.ToDecimal(Data.InvCadUsdRate) * Row.Debit : Row.Debit;
                            }
                        }
                        var NewRows = Data.Rows.Where(row => row.LineNo == 0 && row.Price != 0).ToList();
                        int LineNo = 0;
                        // new non gir group Invoices
                        LineNo = _context.tblGirGroupInvoices.Any(inv => inv.GroupID == Data.InvoiceGroupID && inv.CustomerID == Data.InvoiceCustomerID) ? _context.tblGirGroupInvoices.Where(inv => inv.GroupID == Data.InvoiceGroupID && inv.CustomerID == Data.InvoiceCustomerID).Max(inv => inv.LineNo) : 0;
                        foreach (var Newrow in NewRows)
                        {
                            LineNo++;
                            tblGirGroupInvoice Invoice = new tblGirGroupInvoice
                            {
                                Price = Newrow.Price,
                                PriceChange = (CurrChanged == true && Newrow.Currency == "CAD" && Data.InvCadUsdRate != null && Data.InvCadUsdRate > 0) ? Convert.ToDecimal(Data.InvCadUsdRate) * Newrow.PriceChange : Newrow.PriceChange,
                                Quantity = Newrow.Qty,
                                Description = Newrow.Description,
                                DebCre = Newrow.CrDeb,
                                Currency = Newrow.Currency,
                                Credit = (CurrChanged == true && Newrow.Currency == "CAD" && Data.InvCadUsdRate != null && Data.InvCadUsdRate > 0) ? Convert.ToDecimal(Data.InvCadUsdRate) * Newrow.Credit : Newrow.Credit,
                                Debit = (CurrChanged == true && Newrow.Currency == "CAD" && Data.InvCadUsdRate != null && Data.InvCadUsdRate > 0) ? Convert.ToDecimal(Data.InvCadUsdRate) * Newrow.Debit : Newrow.Debit,
                                ItemTypeID = 0,
                                GroupID = Data.InvoiceGroupID,
                                CustomerID = Data.InvoiceCustomerID,
                                LineNo = LineNo,
                            };
                            _context.tblGirGroupInvoices.Add(Invoice);
                        }
                    }
                    _context.SaveChanges();
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    Error.Message = ex.Message;
                    Error.errorCode = 1245;
                    logger.Error(ex.ToMessageAndCompleteStacktrace());
                    transaction.Rollback();
                }
            }
            if (Group.IsGir == false)
            {
                IQueryable<tblGroupInvoice> GroupInv = _context.tblGroupInvoices.AsQueryable();
                GroupInv = GroupInv.Where(Inv => Inv.GroupID == Data.InvoiceGroupID);
                var InvData = InitOperationInvoiceBData(GroupInv, Data.InvoiceGroupID);
                InvData.Error = Error;
                return InvData;
            }
            else
            {
                IQueryable<tblGirGroupInvoice> GirInv = _context.tblGirGroupInvoices.AsQueryable();
                GirInv = GirInv.Where(Inv => Inv.GroupID == Data.InvoiceGroupID && Inv.CustomerID == Data.InvoiceCustomerID);
                var InvData = InitOperationGirInvoiceBData(GirInv, Data.InvoiceGroupID, Data.InvoiceCustomerID);
                InvData.Error = Error;
                return InvData;
            }
        }
        #endregion
        #region Amex
        public OperationAmexVendorBData LoadOperationAmexVendors(int VendorID, int GroupID, int CardID, int LineNo, DateTime ArrivalDate, string OperationTabName, string Category, DateTime? Time)
        {
            //CityID
            OperationAmexVendorBData AmexBData = new OperationAmexVendorBData();
            AmexBData.Currency = new Dictionary<int, string>
            {
                {1,"USD"},
                {2,"CAD"},
            };
            var Company = _context.tblCompanies.Where(cmp => cmp.CompanyID == 1).SingleOrDefault();
            if (Company != null)
            {
                AmexBData.CompanyAddress = Company.Address + ", " + Company.City + ", " + Company.StateID + ", " + Company.PostalCode;
                AmexBData.CompanyPhone = Company.PhoneNumber;
                AmexBData.CompanyFax = Company.FaxNumber;
            }
            var Grp = _context.tblGroups.Where(grp => grp.GroupID == GroupID).SingleOrDefault();
            var Vnd = _context.tblVendors.Where(vnd => vnd.VendorID == VendorID).SingleOrDefault();
            var Guide = _context.tblGuides.Where(guide => guide.GuideID == VendorID).SingleOrDefault();
            var Card = _context.tblCards.Where(crd => crd.CardID == CardID).SingleOrDefault();
            if (Grp != null)
            {
                AmexBData.GroupCode = Grp.GroupCode;
                AmexBData.GroupID = Grp.GroupID;
                AmexBData.GroupName = Grp.GroupName;
            }
            if (Category == "Guide")
            {
                if (Guide != null)
                {
                    AmexBData.VendorID = Guide.GuideID;
                    AmexBData.VendorName = Guide.FirstName + " " + Guide.LastName;
                }
            }
            else
            {
                if (Vnd != null)
                {
                    AmexBData.VendorID = Vnd.VendorID;
                    AmexBData.VendorName = Vnd.VendorName;
                }
            }
            if (Card != null)
            {
                var CardType = _context.tblCardTypes.Where(crdt => crdt.CardTypeID == Card.CardTypeID).SingleOrDefault();
                if (CardType != null)
                {
                    AmexBData.CardType = CardType.CardType;
                }
                AmexBData.CardNumber = Card.CardNumber;
                CardID = Card.CardID;
                AmexBData.PlaceHolderName = Card.PlaceHolderName;
                AmexBData.CardValidToDate = Card.CardValidToDate;
            }
            var AmexVendor = _context.tblAuthForms.AsQueryable();
            if (AmexVendor.Any(amex => amex.VendorID == VendorID && amex.GroupID == GroupID && amex.CardID == CardID && amex.LineNo == LineNo && amex.ArrivalDate == ArrivalDate && amex.Category == Category))
            {
                var AmexVendorList = AmexVendor.Where(amex => amex.VendorID == VendorID && amex.GroupID == GroupID && amex.CardID == CardID && amex.LineNo == LineNo && amex.ArrivalDate == ArrivalDate && amex.Category == Category).ToList();
                var Data = AmexVendorList.Count > 0 ? (from AmxVnd in AmexVendorList
                                                       select new OperationAmexVendorBData
                                                       {
                                                           AmexVendorID = AmxVnd.AuthFormID,
                                                           PreparedBy = AmxVnd.Preparedby,
                                                           Date = AmxVnd.PaymentDate,
                                                           Attention = AmxVnd.Attention,
                                                           ExpectedCommissionAmount = AmxVnd.ExpCommAmt,
                                                           CommissionableAmount = AmxVnd.CommAmt,
                                                           CommissionAmountReceived = AmxVnd.CommAmtRec,
                                                           CommissionReceivedDate = AmxVnd.CommRecDate,
                                                           Charged = AmxVnd.Charged,
                                                           LineNo = AmxVnd.LineNo,
                                                           CardID = AmxVnd.CardID,
                                                           IsItCommissionable = AmxVnd.IsComm,
                                                           AuthorizedAmount = AmxVnd.AuthAmt,
                                                           PaymentFor = AmxVnd.PaymentFor,
                                                           SelectedCurrency = AmxVnd.Curr,
                                                           ArrivalDate = ArrivalDate,
                                                           Time = Time,
                                                           Category = AmxVnd.Category,
                                                       }).FirstOrDefault() : null;
                if (Time != null)
                {
                    foreach (var Row in AmexVendorList)
                    {
                        if (Convert.ToDateTime(Row.Time).Hour == Convert.ToDateTime(Time).Hour && Convert.ToDateTime(Row.Time).Minute == Convert.ToDateTime(Time).Minute)
                        {
                            Data = new OperationAmexVendorBData()
                                   {
                                       AmexVendorID = Row.AuthFormID,
                                       PreparedBy = Row.Preparedby,
                                       Date = Row.PaymentDate,
                                       Attention = Row.Attention,
                                       ExpectedCommissionAmount = Row.ExpCommAmt,
                                       CommissionableAmount = Row.CommAmt,
                                       CommissionAmountReceived = Row.CommAmtRec,
                                       CommissionReceivedDate = Row.CommRecDate,
                                       Charged = Row.Charged,
                                       LineNo = Row.LineNo,
                                       CardID = Row.CardID,
                                       IsItCommissionable = Row.IsComm,
                                       AuthorizedAmount = Row.AuthAmt,
                                       PaymentFor = Row.PaymentFor,
                                       SelectedCurrency = Row.Curr,
                                       ArrivalDate = ArrivalDate,
                                       Time = Row.Time,
                                       Category = Row.Category,
                                   };
                            break;
                        }
                    }
                }
                if (Data != null)
                {
                    AmexBData.AmexVendorID = Data.AmexVendorID;
                    AmexBData.PreparedBy = Data.PreparedBy;
                    AmexBData.Date = Data.Date;
                    AmexBData.Category = Data.Category;
                    AmexBData.Attention = Data.Attention;
                    AmexBData.ExpectedCommissionAmount = Data.ExpectedCommissionAmount;
                    AmexBData.CommissionableAmount = Data.CommissionableAmount;
                    AmexBData.CommissionAmountReceived = Data.CommissionAmountReceived;
                    AmexBData.CommissionReceivedDate = Data.CommissionReceivedDate;
                    AmexBData.Charged = Data.Charged;
                    AmexBData.IsItCommissionable = Data.IsItCommissionable;
                    AmexBData.AuthorizedAmount = Data.AuthorizedAmount;
                    AmexBData.PaymentFor = Data.PaymentFor;
                    AmexBData.LineNo = Data.LineNo;
                    AmexBData.CardID = Data.CardID;
                    AmexBData.SelectedCurrency = Data.SelectedCurrency;
                    AmexBData.ArrivalDate = ArrivalDate;
                    AmexBData.Time = Time;
                }
                return AmexBData;
            }
            else
            {
                AmexBData.AmexVendorID = -1;
                return AmexBData;
            }
        }
        public ErrorBInfo SaveOperationAmexVendorDetailsData(OperationAmexVendorBData Data)
        {
            ErrorBInfo Error = new ErrorBInfo();
            using (var transaction = _context.Database.BeginTransaction(IsolationLevel.Serializable))
            {
                try
                {
                    var CardTypeCode = _context.tblCardTypes.Where(ctype => ctype.CardTypeID == Data.CardID).Select(ctype => ctype.CardTypeCode).SingleOrDefault();
                    var EditList = (from amx in _context.tblAuthForms
                                    where amx.VendorID == Data.VendorID
                                    && amx.GroupID == Data.GroupID
                                    && amx.ArrivalDate == Data.ArrivalDate
                                    && amx.Category == Data.Category
                                    && amx.LineNo == Data.LineNo
                                    select amx).ToList();
                    var Edit = EditList.Count > 0 ? EditList.FirstOrDefault() : null;
                    if (Data.Time != null)
                    {
                        foreach (var Row in EditList)
                        {
                            if (Convert.ToDateTime(Row.Time).Hour == Convert.ToDateTime(Data.Time).Hour && Convert.ToDateTime(Row.Time).Minute == Convert.ToDateTime(Data.Time).Minute)
                            {
                                Edit = Row;
                                break;
                            }
                        }

                    }
                    if (Edit == null)
                    {
                        tblAuthForm NewAmex = new tblAuthForm()
                        {
                            VendorID = Data.VendorID,
                            GroupID = Data.GroupID,
                            CardID = Data.CardID,
                            Preparedby = Data.PreparedBy,
                            PaymentDate = Data.Date,
                            Attention = Data.Attention,
                            ExpCommAmt = Data.ExpectedCommissionAmount,
                            CommAmtRec = Data.CommissionAmountReceived,
                            CommAmt = Data.CommissionableAmount,
                            CommRecDate = Data.CommissionReceivedDate,
                            Charged = Data.Charged,
                            IsComm = Data.IsItCommissionable,
                            AuthAmt = Data.AuthorizedAmount,
                            PaymentFor = Data.PaymentFor,
                            LineNo = Data.LineNo,
                            Curr = Data.SelectedCurrency,
                            ArrivalDate = Data.ArrivalDate,
                            Time = Data.Time,
                            Category = Data.Category,
                        };
                        _context.tblAuthForms.Add(NewAmex);
                    }
                    else
                    {
                        Edit.VendorID = Data.VendorID;
                        Edit.GroupID = Data.GroupID;
                        Edit.LineNo = Data.LineNo;
                        Edit.CardID = Data.CardID;
                        Edit.Preparedby = Data.PreparedBy;
                        Edit.PaymentDate = Data.Date;
                        Edit.Attention = Data.Attention;
                        Edit.ExpCommAmt = Data.ExpectedCommissionAmount;
                        Edit.CommAmtRec = Data.CommissionAmountReceived;
                        Edit.CommAmt = Data.CommissionableAmount;
                        Edit.CommRecDate = Data.CommissionReceivedDate;
                        Edit.Charged = Data.Charged;
                        Edit.IsComm = Data.IsItCommissionable;
                        Edit.AuthAmt = Data.AuthorizedAmount;
                        Edit.PaymentFor = Data.PaymentFor;
                        Edit.Curr = Data.SelectedCurrency;
                        Edit.ArrivalDate = Data.ArrivalDate;
                        Edit.Time = Data.Time;
                        Edit.Category = Data.Category;
                    }
                    switch (Data.OperationTabName)
                    {
                        case "Hotel":
                            {
                                var EditVconf = (from vcnf in _context.tblVendorConfirms where vcnf.VendorID == Data.VendorID && vcnf.GroupID == Data.GroupID && vcnf.ArrivalDate == Data.ArrivalDate select vcnf).SingleOrDefault();
                                if (EditVconf != null)
                                {
                                    switch (Data.LineNo)
                                    {
                                        case 1:
                                            {
                                                EditVconf.FirstPayment = Data.AuthorizedAmount;
                                                EditVconf.FirstPaymentDate = Data.Date;
                                                EditVconf.FirstPaymentMethod = CardTypeCode;
                                            }
                                            break;
                                        case 2:
                                            {
                                                EditVconf.SecondPayment = Data.AuthorizedAmount;
                                                EditVconf.SecondPaymentDate = Data.Date;
                                                EditVconf.SecondPaymentMethod = CardTypeCode;
                                            }
                                            break;
                                        case 3:
                                            {
                                                EditVconf.ThirdPayment = Data.AuthorizedAmount;
                                                EditVconf.ThirdPaymentDate = Data.Date;
                                                EditVconf.ThirdPaymentMethod = CardTypeCode;
                                            }
                                            break;
                                        default:
                                            break;
                                    }
                                }
                            }
                            break;
                        case "Attractions":
                            {
                                var EditAttrconf = (from Attrcnf in _context.tblAttractionsConfirms where Attrcnf.VendorID == Data.VendorID && Attrcnf.GroupID == Data.GroupID && Attrcnf.StartDate == Data.ArrivalDate select Attrcnf).SingleOrDefault();
                                if (EditAttrconf != null)
                                {
                                    switch (Data.LineNo)
                                    {
                                        case 1:
                                            {
                                                EditAttrconf.FirstPayment = Data.AuthorizedAmount;
                                                EditAttrconf.FirstPaymentDate = Data.Date;
                                                EditAttrconf.FirstPaymentMethod = CardTypeCode;
                                            }
                                            break;
                                        case 2:
                                            {
                                                EditAttrconf.SecondPayment = Data.AuthorizedAmount;
                                                EditAttrconf.SecondPaymentDate = Data.Date;
                                                EditAttrconf.SecondPaymentMethod = CardTypeCode;
                                            }
                                            break;
                                        case 3:
                                            {
                                                EditAttrconf.ThirdPayment = Data.AuthorizedAmount;
                                                EditAttrconf.ThirdPaymentDate = Data.Date;
                                                EditAttrconf.ThirdPaymentMethod = CardTypeCode;
                                            }
                                            break;
                                        default:
                                            break;
                                    }
                                }
                            }
                            break;
                        case "Restaurants":
                            {
                                var EditRestconf = (from Restrcnf in _context.tblRestaurantsConfirms where Restrcnf.VendorID == Data.VendorID && Restrcnf.GroupID == Data.GroupID && Restrcnf.StartDate == Data.ArrivalDate && Restrcnf.Category == Data.Category select Restrcnf).SingleOrDefault();
                                if (EditRestconf != null)
                                {
                                    switch (Data.LineNo)
                                    {
                                        case 1:
                                            {
                                                EditRestconf.FirstPayment = Data.AuthorizedAmount;
                                                EditRestconf.FirstPaymentDate = Data.Date;
                                                EditRestconf.FirstPaymentMethod = CardTypeCode;
                                            }
                                            break;
                                        case 2:
                                            {
                                                EditRestconf.SecondPayment = Data.AuthorizedAmount;
                                                EditRestconf.SecondPaymentDate = Data.Date;
                                                EditRestconf.SecondPaymentMethod = CardTypeCode;
                                            }
                                            break;
                                        case 3:
                                            {
                                                EditRestconf.ThirdPayment = Data.AuthorizedAmount;
                                                EditRestconf.ThirdPaymentDate = Data.Date;
                                                EditRestconf.ThirdPaymentMethod = CardTypeCode;
                                            }
                                            break;
                                        default:
                                            break;
                                    }
                                }
                            }
                            break;
                        case "Misc":
                            {
                                var EditMiscconf = (from Misccnf in _context.tblMiscConfirms where Misccnf.VendorID == Data.VendorID && Misccnf.GroupID == Data.GroupID && Misccnf.StartDate == Data.ArrivalDate select Misccnf).SingleOrDefault();
                                if (EditMiscconf != null)
                                {
                                    switch (Data.LineNo)
                                    {
                                        case 1:
                                            {
                                                EditMiscconf.FirstPayment = Data.AuthorizedAmount;
                                                EditMiscconf.FirstPaymentDate = Data.Date;
                                                EditMiscconf.FirstPaymentMethod = CardTypeCode;
                                            }
                                            break;
                                        case 2:
                                            {
                                                EditMiscconf.SecondPayment = Data.AuthorizedAmount;
                                                EditMiscconf.SecondPaymentDate = Data.Date;
                                                EditMiscconf.SecondPaymentMethod = CardTypeCode;
                                            }
                                            break;
                                        case 3:
                                            {
                                                EditMiscconf.ThirdPayment = Data.AuthorizedAmount;
                                                EditMiscconf.ThirdPaymentDate = Data.Date;
                                                EditMiscconf.ThirdPaymentMethod = CardTypeCode;
                                            }
                                            break;
                                        default:
                                            break;
                                    }
                                }
                            }
                            break;
                        case "Bus":
                            {
                                var EditBusconfList = (from Buscnf in _context.tblBusConfirms where Buscnf.VendorID == Data.VendorID && Buscnf.GroupID == Data.GroupID && Buscnf.StartDate == Data.ArrivalDate select Buscnf).ToList();
                                var EditBusconf = EditBusconfList.Count > 0 ? EditBusconfList.FirstOrDefault() : null;
                                if (Data.Time != null)
                                {
                                    foreach (var Row in EditBusconfList)
                                    {
                                        if (Convert.ToDateTime(Row.Time).Hour == Convert.ToDateTime(Data.Time).Hour && Convert.ToDateTime(Row.Time).Minute == Convert.ToDateTime(Data.Time).Minute)
                                        {
                                            EditBusconf = Row;
                                            break;
                                        }
                                    }

                                }
                                if (EditBusconf != null)
                                {

                                    switch (Data.LineNo)
                                    {
                                        case 1:
                                            {
                                                EditBusconf.FirstPayment = Data.AuthorizedAmount;
                                                EditBusconf.FirstPaymentDate = Data.Date;
                                                EditBusconf.FirstPaymentMethod = CardTypeCode;
                                            }
                                            break;
                                        case 2:
                                            {
                                                EditBusconf.SecondPayment = Data.AuthorizedAmount;
                                                EditBusconf.SecondPaymentDate = Data.Date;
                                                EditBusconf.SecondPaymentMethod = CardTypeCode;
                                            }
                                            break;
                                        case 3:
                                            {
                                                EditBusconf.ThirdPayment = Data.AuthorizedAmount;
                                                EditBusconf.ThirdPaymentDate = Data.Date;
                                                EditBusconf.ThirdPaymentMethod = CardTypeCode;
                                            }
                                            break;
                                        default:
                                            break;
                                    }
                                }
                            }
                            break;
                        case "Guide":
                            {
                                var EditGuideconfList = (from guidecnf in _context.tblGuideConfirms where guidecnf.GuideID == Data.GuideID && guidecnf.GroupID == Data.GroupID select guidecnf).ToList();
                                var EditGuideconf = EditGuideconfList.Count > 0 ? EditGuideconfList.FirstOrDefault() : null;
                                if (Data.Time != null)
                                {
                                    foreach (var Row in EditGuideconfList)
                                    {
                                        if (Convert.ToDateTime(Row.Time).Hour == Convert.ToDateTime(Data.Time).Hour && Convert.ToDateTime(Row.Time).Minute == Convert.ToDateTime(Data.Time).Minute)
                                        {
                                            EditGuideconf = Row;
                                            break;
                                        }
                                    }

                                }
                                if (EditGuideconf != null)
                                {
                                    switch (Data.LineNo)
                                    {
                                        case 1:
                                            {
                                                EditGuideconf.FirstPayment = Data.AuthorizedAmount;
                                                EditGuideconf.FirstPaymentDate = Data.Date;
                                                EditGuideconf.FirstPaymentMethod = CardTypeCode;
                                            }
                                            break;
                                        case 2:
                                            {
                                                EditGuideconf.SecondPayment = Data.AuthorizedAmount;
                                                EditGuideconf.SecondPaymentDate = Data.Date;
                                                EditGuideconf.SecondPaymentMethod = CardTypeCode;
                                            }
                                            break;
                                        case 3:
                                            {
                                                EditGuideconf.ThirdPayment = Data.AuthorizedAmount;
                                                EditGuideconf.ThirdPaymentDate = Data.Date;
                                                EditGuideconf.ThirdPaymentMethod = CardTypeCode;
                                            }
                                            break;
                                        default:
                                            break;
                                    }
                                }
                            }
                            break;
                        default:
                            break;
                    }
                    _context.SaveChanges();
                    transaction.Commit();
                }
                catch (Exception ex)
                {
                    Error.errorCode = 130;
                    Error.Message = ex.Message;
                    logger.Error(ex.ToMessageAndCompleteStacktrace());
                    transaction.Rollback();
                }
            }
            return Error;
        }
        #endregion
        #region private methods
        private OperationAttrBusConfirmGridBData InitOperationBusConfirmBData(IQueryable<tblBusConfirm> BusConfirm)
        {
            OperationAttrBusConfirmGridBData AttrBusConfData = new OperationAttrBusConfirmGridBData();
            AttrBusConfData.Status = new Dictionary<int, string>();
            AttrBusConfData.Service = new Dictionary<int, string>();
            try
            {
                var AttrBusConf = BusConfirm.SingleOrDefault();
                if (AttrBusConf != null)
                {
                    AttrBusConfData.VendorName = _context.tblVendors.Where(vnd => vnd.VendorID == AttrBusConf.VendorID).Select(vnd => vnd.VendorName).SingleOrDefault();
                    AttrBusConfData.ArrivalDate = AttrBusConf.StartDate;
                    AttrBusConfData.ArrivalTime = AttrBusConf.Time;
                    AttrBusConfData.StatusID = AttrBusConf.StatusID;
                    AttrBusConfData.EmployeeId = AttrBusConf.EmployeeID;
                    AttrBusConfData.Note = AttrBusConf.Notes;
                    AttrBusConfData.GroupID = AttrBusConf.GroupID;
                    AttrBusConfData.GroupCode = _context.tblGroups.Where(grp => grp.GroupID == AttrBusConf.GroupID).SingleOrDefault().GroupCode;
                    AttrBusConfData.VendorID = AttrBusConf.VendorID;
                    AttrBusConfData.VendorConfirmFile = AttrBusConf.BusConfirmFile;
                }
                AttrBusConfData.Status = (from st in _context.tblVConfirmStatus
                                    where st.Active == true
                                    orderby st.StatusOrder
                                    select new
                                    {
                                        Key = st.StatusID,
                                        Value = st.StatusDesc
                                    }).ToDictionary(o => o.Key, o => o.Value);
                AttrBusConfData.Service = (from Serv in _context.tblServices
                                           from SerType in _context.tblServiceTypes
                                           where Serv.ServiceTypeID == SerType.ServiceTypeID
                                           && SerType.VendorTypeID == 1
                                           && Serv.Active == true
                                           && SerType.Active == true
                                           select new
                                           {
                                               Key = Serv.ServiceID,
                                               Value = SerType.ServiceTypeCode + " - " + Serv.ServiceCode,
                                           }).ToDictionary(o => o.Key, o => o.Value);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToMessageAndCompleteStacktrace());
            }
            return AttrBusConfData;
        }
        private OperationAttrBusConfirmGridBData InitOperationAttractionsConfirmBData(IQueryable<tblAttractionsConfirm> AttractionsConfirm)
        {
            OperationAttrBusConfirmGridBData AttrBusConfData = new OperationAttrBusConfirmGridBData();
            AttrBusConfData.Status = new Dictionary<int, string>();
            AttrBusConfData.Service = new Dictionary<int, string>();
            try
            {
                var AttrBusConf = AttractionsConfirm.SingleOrDefault();
                if (AttrBusConf != null)
                {
                    AttrBusConfData.VendorName = _context.tblVendors.Where(vnd => vnd.VendorID == AttrBusConf.VendorID).Select(vnd => vnd.VendorName).SingleOrDefault();
                    AttrBusConfData.ArrivalDate = AttrBusConf.StartDate;
                    AttrBusConfData.ArrivalTime = AttrBusConf.Time;
                    AttrBusConfData.StatusID = AttrBusConf.StatusID;
                    AttrBusConfData.EmployeeId = AttrBusConf.EmployeeID;
                    AttrBusConfData.Note = AttrBusConf.Notes;
                    AttrBusConfData.GroupID = AttrBusConf.GroupID;
                    AttrBusConfData.GroupCode = _context.tblGroups.Where(grp => grp.GroupID == AttrBusConf.GroupID).SingleOrDefault().GroupCode;
                    AttrBusConfData.VendorID = AttrBusConf.VendorID;
                    AttrBusConfData.VendorConfirmFile = AttrBusConf.AttractionsConfirmFile;
                }
                AttrBusConfData.Status = (from st in _context.tblVConfirmStatus
                                          where st.Active == true
                                          orderby st.StatusOrder
                                          select new
                                          {
                                              Key = st.StatusID,
                                              Value = st.StatusDesc
                                          }).ToDictionary(o => o.Key, o => o.Value);
                AttrBusConfData.Service = (from Serv in _context.tblServices
                                           from SerType in _context.tblServiceTypes
                                           where Serv.ServiceTypeID == SerType.ServiceTypeID
                                           && SerType.VendorTypeID == 1
                                           && Serv.Active == true
                                           && SerType.Active == true
                                           select new
                                           {
                                               Key = Serv.ServiceID,
                                               Value = SerType.ServiceTypeCode + " - " + Serv.ServiceCode,
                                           }).ToDictionary(o => o.Key, o => o.Value);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToMessageAndCompleteStacktrace());
            }
            return AttrBusConfData;
        }

        private OperationAttrBusConfirmGridBData InitOperationMiscConfirmBData(IQueryable<tblMiscConfirm> MiscConfirm)
        {
            OperationAttrBusConfirmGridBData AttrBusConfData = new OperationAttrBusConfirmGridBData();
            AttrBusConfData.Status = new Dictionary<int, string>();
            AttrBusConfData.Service = new Dictionary<int, string>();
            try
            {
                var AttrBusConf = MiscConfirm.SingleOrDefault();
                if (AttrBusConf != null)
                {
                    AttrBusConfData.VendorName = _context.tblVendors.Where(vnd => vnd.VendorID == AttrBusConf.VendorID).Select(vnd => vnd.VendorName).SingleOrDefault();
                    AttrBusConfData.ArrivalDate = AttrBusConf.StartDate;
                    AttrBusConfData.ArrivalTime = AttrBusConf.Time;
                    AttrBusConfData.StatusID = AttrBusConf.StatusID;
                    AttrBusConfData.EmployeeId = AttrBusConf.EmployeeID;
                    AttrBusConfData.Note = AttrBusConf.Notes;
                    AttrBusConfData.GroupID = AttrBusConf.GroupID;
                    AttrBusConfData.GroupCode = _context.tblGroups.Where(grp => grp.GroupID == AttrBusConf.GroupID).SingleOrDefault().GroupCode;
                    AttrBusConfData.VendorID = AttrBusConf.VendorID;
                    AttrBusConfData.VendorConfirmFile = AttrBusConf.MiscConfirmFile;
                }
                AttrBusConfData.Status = (from st in _context.tblVConfirmStatus
                                          where st.Active == true
                                          orderby st.StatusOrder
                                          select new
                                          {
                                              Key = st.StatusID,
                                              Value = st.StatusDesc
                                          }).ToDictionary(o => o.Key, o => o.Value);
                AttrBusConfData.Service = (from Serv in _context.tblServices
                                           from SerType in _context.tblServiceTypes
                                           where Serv.ServiceTypeID == SerType.ServiceTypeID
                                           && SerType.VendorTypeID == 1
                                           && Serv.Active == true
                                           && SerType.Active == true
                                           select new
                                           {
                                               Key = Serv.ServiceID,
                                               Value = SerType.ServiceTypeCode + " - " + Serv.ServiceCode,
                                           }).ToDictionary(o => o.Key, o => o.Value);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToMessageAndCompleteStacktrace());
            }
            return AttrBusConfData;
        }
        private OperationAttrBusConfirmGridBData InitOperationRestaurantsConfirmBData(IQueryable<tblRestaurantsConfirm> RestaurantsConfirm)
        {
            OperationAttrBusConfirmGridBData AttrBusConfData = new OperationAttrBusConfirmGridBData();
            AttrBusConfData.Status = new Dictionary<int, string>();
            AttrBusConfData.Service = new Dictionary<int, string>();
            try
            {
                var AttrBusConf = RestaurantsConfirm.SingleOrDefault();
                if (AttrBusConf != null)
                {
                    AttrBusConfData.VendorName = _context.tblVendors.Where(vnd => vnd.VendorID == AttrBusConf.VendorID).Select(vnd => vnd.VendorName).SingleOrDefault();
                    AttrBusConfData.ArrivalDate = AttrBusConf.StartDate;
                    AttrBusConfData.ArrivalTime = AttrBusConf.Time;
                    AttrBusConfData.StatusID = AttrBusConf.StatusID;
                    AttrBusConfData.EmployeeId = AttrBusConf.EmployeeID;
                    AttrBusConfData.Note = AttrBusConf.Notes;
                    AttrBusConfData.GroupID = AttrBusConf.GroupID;
                    AttrBusConfData.GroupCode = _context.tblGroups.Where(grp => grp.GroupID == AttrBusConf.GroupID).SingleOrDefault().GroupCode;
                    AttrBusConfData.VendorID = AttrBusConf.VendorID;
                    AttrBusConfData.VendorConfirmFile = AttrBusConf.RestaurantsConfirmFile;
                }
                AttrBusConfData.Status = (from st in _context.tblVConfirmStatus
                                          where st.Active == true
                                          orderby st.StatusOrder
                                          select new
                                          {
                                              Key = st.StatusID,
                                              Value = st.StatusDesc
                                          }).ToDictionary(o => o.Key, o => o.Value);
                AttrBusConfData.Service = (from Serv in _context.tblServices
                                           from SerType in _context.tblServiceTypes
                                           where Serv.ServiceTypeID == SerType.ServiceTypeID
                                           && SerType.VendorTypeID == 1
                                           && Serv.Active == true
                                           && SerType.Active == true
                                           select new
                                           {
                                               Key = Serv.ServiceID,
                                               Value = SerType.ServiceTypeCode + " - " + Serv.ServiceCode,
                                           }).ToDictionary(o => o.Key, o => o.Value);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToMessageAndCompleteStacktrace());
            }
            return AttrBusConfData;
        }
        private OperationVendorConfirmGridBData InitOperationVendorConfirmBData(IQueryable<tblVendorConfirm> VendConfirm, IQueryable<tblVConfirmDetail> VendConfirmDet)
        {
            OperationVendorConfirmGridBData VConfData = new OperationVendorConfirmGridBData();
            VConfData.Status = new Dictionary<int, string>();
            VConfData.Service = new Dictionary<int, string>();
            VConfData.Rows = new List<OperationVendorConfirmGridRowBData>();
            try
            {
                var VendConf = VendConfirm.SingleOrDefault();
                if (VendConf != null)
                {
                    VConfData.VendorName = _context.tblVendors.Where(vnd => vnd.VendorID == VendConf.VendorID).Select(vnd => vnd.VendorName).SingleOrDefault();
                    VConfData.ArrivalDate = VendConf.ArrivalDate;
                    VConfData.ArrivalTime = VendConf.ArrivalTime;
                    VConfData.DepartureDate = VendConf.DepartureDate;
                    VConfData.DepartureTime = VendConf.DepartureTime;
                    VConfData.Voucher = VendConf.Voucher;
                    VConfData.StatusID = VendConf.StatusID;
                    VConfData.ConfirmedBy = VendConf.ConfirmedBy;
                    VConfData.ConfirmDate = VendConf.ConfirmDate;
                    VConfData.TourLeader = VendConf.Tourleader;
                    VConfData.EmployeeId = VendConf.EmployeeID;
                    VConfData.IssueDate = VendConf.DateIssued;
                    VConfData.Rooms = VendConf.Rooms;
                    VConfData.Pax = VendConf.Pax;
                    VConfData.PaxPlus = VendConf.PaxPlus;
                    VConfData.Note = VendConf.Notes;
                    VConfData.Luggage = VendConf.Luggage;
                    VConfData.Tax = VendConf.Tax;
                    VConfData.OccTax = VendConf.OccTax;
                    VConfData.Gratuity = VendConf.Gratuity;
                    VConfData.GroupID = VendConf.GroupID;
                    VConfData.GroupCode = _context.tblGroups.Where(grp => grp.GroupID == VendConf.GroupID).SingleOrDefault().GroupCode;
                    VConfData.VendorID = VendConf.VendorID;
                    VConfData.VendorConfirmFile = VendConf.VendorConfirmFile;
                    // VConfData.Employee = VendConf.EmployeeID != null? _context.tblEmployees.Where(emp=>emp.EmployeeID == VendConf.EmployeeID).SingleOrDefault()
                }
                if (VConfData.EmployeeId != null && _context.tblEmployees.Where(emp => emp.EmployeeID == VConfData.EmployeeId).SingleOrDefault() != null)
                    VConfData.Employee = _context.tblEmployees.Where(emp => emp.EmployeeID == VConfData.EmployeeId).SingleOrDefault().EmailName;
                VConfData.Status = (from st in _context.tblVConfirmStatus
                                    where st.Active == true
                                    orderby st.StatusOrder
                                    select new
                                    {
                                        Key = st.StatusID,
                                        Value = st.StatusDesc
                                    }).ToDictionary(o => o.Key, o => o.Value);
                VConfData.Service = (from Serv in _context.tblServices
                                     from SerType in _context.tblServiceTypes
                                     where Serv.ServiceTypeID == SerType.ServiceTypeID
                                     && SerType.VendorTypeID == 1
                                     && Serv.Active == true
                                     && SerType.Active == true
                                     select new
                                     {
                                         Key = Serv.ServiceID,
                                         Value = SerType.ServiceTypeCode + " - " + Serv.ServiceCode,
                                     }).ToDictionary(o => o.Key, o => o.Value);
                VConfData.Rows = (from VConfDet in VendConfirmDet
                                  from Serv in _context.tblServices
                                  from SerType in _context.tblServiceTypes
                                  where Serv.ServiceTypeID == SerType.ServiceTypeID
                                  && Serv.Active == true
                                  && SerType.Active == true
                                  && Serv.ServiceID == VConfDet.ServiceID
                                  orderby VConfDet.LineNo
                                  select new OperationVendorConfirmGridRowBData
                                  {
                                     // VendorID = VConfDet.VendorID,
                                      Product = VConfDet.ProductID,
                                      IsRow = VConfDet.ManualFlg,
                                      VendorTypeID = SerType.VendorTypeID,
                                      SelServiceID = Serv.ServiceID,
                                      SelService = SerType.ServiceTypeCode + " - " + Serv.ServiceCode,
                                      LineNo = VConfDet.LineNo,
                                      StartDate = VConfDet.StartDate,
                                      EndDate = VConfDet.EndDate,
                                      Description = VConfDet.Description,
                                      XQty = VConfDet.XQty,
                                      Qty = VConfDet.Qty,
                                      Manual = VConfDet.ManualFlg,
                                      Price = VConfDet.Price,
                                  }).ToList();
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToMessageAndCompleteStacktrace());
            }
            return VConfData;
        }
        private OperationInvoiceBData InitOperationInvoiceBData(IQueryable<tblGroupInvoice> GrInvoice, int GroupID)
        {
            OperationInvoiceBData InvoiceBData = new OperationInvoiceBData();
            InvoiceBData.Error = new ErrorBInfo();
            var Group = _context.tblGroups.Where(gr => gr.GroupID == GroupID).SingleOrDefault();
            InvoiceBData.InvType = new Dictionary<int, string>();
            InvoiceBData.InvType = (from type in _context.tblInvoiceItemTypes
                                    select new
                                    {
                                        Key = type.ItemTypeID,
                                        Value = type.ItemTypeDesc
                                    }).ToDictionary(o => o.Key, o => o.Value);
            InvoiceBData.InvSalesPerson = new Dictionary<int, string>();
            InvoiceBData.InvSalesPerson = (from user in _context.Users
                                           from emp in _context.tblEmployees
                                           where user.EmployeeID == emp.EmployeeID && emp.Active == true
                                           orderby emp.FirstName, emp.LastName
                                           select new
                                           {
                                               Key = emp.EmployeeID,
                                               Value = emp.FirstName + " " + emp.LastName,
                                           }).ToDictionary(o => o.Key, o => o.Value);
            int CustomerID = 0;
            if (Group != null)
                if(_context.tblCustomers.Any(cust => cust.CustomerID == Group.CustomerID && cust.Active == true))
                    CustomerID = _context.tblCustomers.Where(cust => cust.CustomerID == Group.CustomerID).SingleOrDefault().CustomerID;
            InvoiceBData.ContactPerson = new Dictionary<int, string>();
            InvoiceBData.ContactPerson = (from contact in _context.tblCustomerContacts
                                          where contact.CustomerID == CustomerID
                                          orderby contact.CCID
                                          select new
                                          {
                                              Key = contact.CCID,
                                              Value = contact.Name,
                                          }).ToDictionary(o => o.Key, o => o.Value);
            InvoiceBData.InvBanks = new Dictionary<int, string>();
            InvoiceBData.InvBanks = (from bank in _context.tblBanks
                                     where bank.Active == true
                                     select new
                                     {
                                         Key = bank.BankID,
                                         Value = bank.BankName
                                     }).ToDictionary(o => o.Key, o => o.Value);
            InvoiceBData.InvPaymentTerms = new List<string>();
            InvoiceBData.InvPaymentTerms = (from Pterms in _context.tblPayTerms
                                            select Pterms.PayTerms).ToList();

            if (Group != null)
            {
                InvoiceBData.InvTotalDeposit = _context.tblDeposits.Where(dep => dep.GroupID == Group.GroupID).Sum(dep => dep.Received);
                InvoiceBData.InvTotalRefund = _context.tblDeposits.Where(dep => dep.GroupID == Group.GroupID).Sum(dep => dep.Refunded);
                InvoiceBData.InvGroupQuotaID = Group.QuotaID;
                InvoiceBData.InvIsGroupGir = Group.IsGir;
                InvoiceBData.InvCadUsdRate = Group.UsdCadRate;
                InvoiceBData.InvoiceGroupID = Group.GroupID;
                InvoiceBData.InvoiceArrivalDate = Group.ArrivalDate;
                InvoiceBData.InvoiceGroupCode = Group.GroupCode;
                InvoiceBData.InvoiceGroupName = Group.GroupName;
                InvoiceBData.InvoiceCustomer = _context.tblCustomers.Any(cust => cust.CustomerID == Group.CustomerID) ? _context.tblCustomers.Where(cust => cust.CustomerID == Group.CustomerID).SingleOrDefault().OrganizationName : "";
                InvoiceBData.InvoiceComment = Group.InvComm;
                InvoiceBData.PerformaComment = Group.ProComm;
                InvoiceBData.InvoiceDate = Group.InvDate;
                InvoiceBData.FinalPayment = Group.FinalPayment;
                InvoiceBData.DepositDue = Group.DepositDue;
                InvoiceBData.DepositM = Group.DepositM;
                InvoiceBData.DepositAmount = Group.DepositAmt;
                InvoiceBData.SelectedInvSalesPerson = Group.InvEmployeeID;
                InvoiceBData.SelectedContactPerson = Group.CCID;
                InvoiceBData.InvProforma = Group.ProInv;
                InvoiceBData.SelectedInvPaymentTerms = Group.PayTerms;
                InvoiceBData.SelectedInvBank = Group.BankID;
                InvoiceBData.InvRateChangeDate = Group.RateChangeDate;
                var InvNo = _context.tblInvoiceNoes.Where(inv => inv.InvDate == Group.InvDate && inv.GroupID == Group.GroupID && inv.ProInv == Group.ProInv).SingleOrDefault();
                if (InvNo != null)
                    InvoiceBData.InvoiceNo = InvNo.InvNo;
                // InvoiceBData.InvDepositeDate = 
            }
            InvoiceBData.Rows = new List<OperationInvoiceGridBData>();
            InvoiceBData.Rows = (from GInv in GrInvoice
                                 from InvType in _context.tblInvoiceItemTypes
                                 where InvType.ItemTypeID == GInv.ItemTypeID
                                 select new OperationInvoiceGridBData()
                                 {
                                     LineNo = GInv.LineNo,
                                     Qty = GInv.Quantity,
                                     SelTypeID = GInv.ItemTypeID,
                                     VendorID = GInv.VendorID,
                                     SelType = InvType.ItemTypeDesc,
                                     Description = GInv.Description,
                                     Price = GInv.Price,
                                     PriceChange = GInv.PriceChange,
                                     Debit = GInv.Debit,
                                     Credit = GInv.Credit,
                                     CrDeb = GInv.DebCre,
                                     Currency = GInv.Currency,
                                 }).ToList();
            return InvoiceBData;
        }
        private OperationInvoiceBData InitOperationGirInvoiceBData(IQueryable<tblGirGroupInvoice> GrInvoice, int GroupID, int CustomerID)
        {
            OperationInvoiceBData InvoiceBData = new OperationInvoiceBData();
            InvoiceBData.Error = new ErrorBInfo();
            var GirDetails = _context.tblGirGroupDetails.Where(GirDet => GirDet.GroupID == GroupID && GirDet.CustomerID == CustomerID).SingleOrDefault();
            InvoiceBData.InvType = new Dictionary<int, string>();
            InvoiceBData.InvType = (from type in _context.tblInvoiceItemTypes
                                    select new
                                    {
                                        Key = type.ItemTypeID,
                                        Value = type.ItemTypeDesc
                                    }).ToDictionary(o => o.Key, o => o.Value);
            InvoiceBData.InvSalesPerson = new Dictionary<int, string>();
            InvoiceBData.InvSalesPerson = (from user in _context.Users
                                           from emp in _context.tblEmployees
                                           where user.EmployeeID == emp.EmployeeID && emp.Active == true
                                           orderby emp.FirstName, emp.LastName
                                           select new
                                           {
                                               Key = emp.EmployeeID,
                                               Value = emp.FirstName + " " + emp.LastName,
                                           }).ToDictionary(o => o.Key, o => o.Value);
            InvoiceBData.ContactPerson = new Dictionary<int, string>();
            InvoiceBData.ContactPerson = (from contact in _context.tblCustomerContacts
                                          where contact.CustomerID == CustomerID
                                          orderby contact.CCID
                                          select new
                                          {
                                              Key = contact.CCID,
                                              Value = contact.Name,
                                          }).ToDictionary(o => o.Key, o => o.Value);
            InvoiceBData.InvBanks = new Dictionary<int, string>();
            InvoiceBData.InvBanks = (from bank in _context.tblBanks
                                     where bank.Active == true
                                     select new
                                     {
                                         Key = bank.BankID,
                                         Value = bank.BankName
                                     }).ToDictionary(o => o.Key, o => o.Value);
            InvoiceBData.InvPaymentTerms = new List<string>();
            InvoiceBData.InvPaymentTerms = (from Pterms in _context.tblPayTerms
                                            select Pterms.PayTerms).ToList();

            if (GirDetails != null)
            {
                var Group = _context.tblGroups.Where(grp => grp.GroupID == GroupID).SingleOrDefault();
                InvoiceBData.InvTotalDeposit = _context.tblDeposits.Where(dep => dep.GroupID == GirDetails.GroupID).Sum(dep => dep.Received);
                InvoiceBData.InvTotalRefund = _context.tblDeposits.Where(dep => dep.GroupID == GirDetails.GroupID).Sum(dep => dep.Refunded);
                InvoiceBData.InvGroupQuotaID = Group.QuotaID;
                InvoiceBData.InvIsGroupGir = Group.IsGir;
                InvoiceBData.FinalPayment = GirDetails.FinalPayment;
                InvoiceBData.InvCadUsdRate = GirDetails.UsdCadRate;
                InvoiceBData.InvRateChangeDate = GirDetails.RateChangeDate;
                InvoiceBData.InvoiceGroupID = GirDetails.GroupID;
                InvoiceBData.InvoiceCustomerID = GirDetails.CustomerID;
                InvoiceBData.InvoiceArrivalDate = Group.ArrivalDate;
                InvoiceBData.InvoiceGroupCode = Group.GroupCode;
                InvoiceBData.InvoiceGroupName = Group.GroupName;
                InvoiceBData.InvoiceCustomer = _context.tblCustomers.Any(cust => cust.CustomerID == CustomerID) ? _context.tblCustomers.Where(cust => cust.CustomerID == CustomerID).SingleOrDefault().OrganizationName : "";
                InvoiceBData.InvoiceComment = GirDetails.InvComm;
                InvoiceBData.PerformaComment = GirDetails.ProComm;
                InvoiceBData.InvoiceDate = GirDetails.InvDate;
                InvoiceBData.DepositDue = GirDetails.DepositDue;
                InvoiceBData.DepositM = GirDetails.DepositM;
                InvoiceBData.DepositAmount = GirDetails.DepositAmt;
                InvoiceBData.SelectedInvSalesPerson = GirDetails.InvEmployeeID;
                InvoiceBData.SelectedContactPerson = GirDetails.CCID;
                InvoiceBData.InvProforma = GirDetails.ProInv;
                InvoiceBData.SelectedInvPaymentTerms = GirDetails.PayTerms;
                InvoiceBData.SelectedInvBank = GirDetails.BankID;
                var InvNo = _context.tblInvoiceNoes.Where(inv => inv.InvDate == Group.InvDate && inv.GroupID == Group.GroupID && inv.ProInv == Group.ProInv).SingleOrDefault();
                if (InvNo != null)
                    InvoiceBData.InvoiceNo = InvNo.InvNo;
                // InvoiceBData.InvDepositeDate = 
            }
            InvoiceBData.Rows = new List<OperationInvoiceGridBData>();
            InvoiceBData.Rows = (from GInv in GrInvoice
                                 from InvType in _context.tblInvoiceItemTypes
                                 where InvType.ItemTypeID == GInv.ItemTypeID
                                 select new OperationInvoiceGridBData()
                                 {
                                     LineNo = GInv.LineNo,
                                     Qty = GInv.Quantity,
                                     SelTypeID = GInv.ItemTypeID,
                                     VendorID = GInv.VendorID,
                                     SelType = InvType.ItemTypeDesc,
                                     Description = GInv.Description,
                                     Price = GInv.Price,
                                     PriceChange = GInv.PriceChange,
                                     Debit = GInv.Debit,
                                     Credit = GInv.Credit,
                                     CrDeb = GInv.DebCre,
                                     Currency = GInv.Currency,
                                 }).ToList();
            return InvoiceBData;
        }
        private OperationGVendorRoomGridBData InitOperationGroupVendorGridBData(IQueryable<tblVConfirmRoom> VConfRoom, IQueryable<tblVendorConfirm> VConf)
        {
            OperationGVendorRoomGridBData GrVendorGridData = new OperationGVendorRoomGridBData();
            GrVendorGridData.Rows = new List<OperationGVendorRoomGridRowBData>();
            GrVendorGridData.Roomtype = new Dictionary<int, string>();
            var VendConf = VConf.SingleOrDefault();
            if (VendConf != null)
            {
                GrVendorGridData.VendorName = _context.tblVendors.Where(vnd => vnd.VendorID == VendConf.VendorID).Select(vnd => vnd.VendorName).SingleOrDefault();
                GrVendorGridData.RoomListNotes = VendConf.RoomListNotes;
                GrVendorGridData.RoomListEditNotes = VendConf.RoomListEditNotes;
                GrVendorGridData.PorterageNotes = VendConf.PorterageNotes;
                GrVendorGridData.PorterageFlag = VendConf.PorterageFlag;
            }
            // title
            GrVendorGridData.Title = (from title in _context.tblTitles
                                      from serv in _context.tblServices
                                      where title.ServiceID == serv.ServiceID
                                      && serv.Active == true
                                      && serv.ServiceTypeID == 1
                                      select new TitleInfo { ServiceCode = serv.ServiceCode, Title = title.Title }).ToList();
            // room type
            var service = _context.tblServices.Where(obj => obj.ServiceTypeID == 1 && obj.ServiceID != 103 && obj.Active == true).Select(obj => new { ServId = obj.ServiceID, RoomType = obj.ServiceCode }).ToList();
            foreach (var serv in service)
            {
                GrVendorGridData.Roomtype.Add(serv.ServId, serv.RoomType);
            }
            GrVendorGridData.Rows = (from ConfRoom in VConfRoom
                                     from Serv in _context.tblServices
                                     where Serv.ServiceID == ConfRoom.ServiceID
                                     && Serv.Active == true
                                     orderby ConfRoom.LineNo
                                     select new OperationGVendorRoomGridRowBData
                                     {
                                         GroupID = ConfRoom.GroupID,
                                         LineNo = ConfRoom.LineNo,
                                         VendorID = ConfRoom.VendorID,
                                         Names = ConfRoom.Names,
                                         Notes = ConfRoom.Notes,
                                         NumOfPerson = ConfRoom.NoOfPerson,
                                         ServiceID = ConfRoom.ServiceID,
                                         SelService = Serv.ServiceCode,
                                         Title = ConfRoom.Title,
                                         ArrivalDate = ConfRoom.CheckInDate,
                                         DepartureDate = ConfRoom.CheckOutDate,
                                     }).ToList();
            return GrVendorGridData;
        }
        private void InitOperationHotelGridBData(OperationHotelGridBData Hoteldata, IQueryable<tblVendorConfirm> Vconfirm, IQueryable<tblGroup> Group, string UserName)
        {
            Hoteldata.VendorInfo = new List<OperationHotelVendorInfoBData>();
            Hoteldata.GroupStatus = new Dictionary<int, string>();
            Hoteldata.VendorStatus = new Dictionary<int, string>();
            Hoteldata.PayMethod = new Dictionary<int, string>();
            Hoteldata.SearchCity = new Dictionary<int, string>();
            Hoteldata.GroupCode = new Dictionary<int, string>();
            Hoteldata.GroupName = new Dictionary<int, string>();
            Hoteldata.CustomerCode = new Dictionary<int, string>();
            Hoteldata.VendorName = new Dictionary<int, string>();
            Hoteldata.ArrivalCity = new List<string>();
            Hoteldata.DayofArrival = new Dictionary<int, string>();
            Hoteldata.MonthofArrival = new Dictionary<int, string>();
            Hoteldata.VendorCity = new List<string>();
            Hoteldata.EstRoomNumber = new List<double?>();
            Hoteldata.SearchNationality = new Dictionary<int, string>();
            Hoteldata.Employee = new Dictionary<int, string>();
            // Employee
            var EmpID = _context.Users.Where(usr => usr.UserName == UserName).Select(usr => usr.EmployeeID).SingleOrDefault();
            var SupEmp = _context.tblSupEmployees.Where(sup => sup.EmployeeID == EmpID).Select(sup => sup.SupervisorID).ToList();
            Hoteldata.Employee = (from user in _context.Users
                                  from emp in _context.tblEmployees
                                  where user.EmployeeID == emp.EmployeeID && emp.Active == true &&  SupEmp.Contains((int)user.EmployeeID)
                                  orderby emp.FirstName, emp.LastName
                                  select new
                                  {
                                      Key = emp.EmployeeID,
                                      Value = emp.FirstName + " " + emp.LastName,
                                  }).ToDictionary(o => o.Key, o => o.Value);

            // Vendor Info init
            Hoteldata.VendorInfo = (from vnd in _context.tblVendors
                                    where vnd.VendorTypeID == 1 
                                    && vnd.Active == true 
                                    && vnd.VendorName != null 
                                    && vnd.VendorName.Length > 5
                                    select new OperationHotelVendorInfoBData
                                    {
                                        VendorID = vnd.VendorID,
                                        VendorName = vnd.VendorName,
                                        VendorCity = vnd.City,
                                        VendorAddress = vnd.Address,
                                        VendorContactPerson = vnd.ContactName,
                                        VendorEmail = vnd.EmailNameSales,
                                        VendorPhone = vnd.PhoneSales,
                                        IsFind = vnd.IsFind
                                    }).ToList();
            // group status init
            Hoteldata.GroupStatus = (from grSt in _context.tblGroupStatus
                                     orderby grSt.StatusID
                                     select new { Key = grSt.StatusID, Value = grSt.StatusDesc }).ToDictionary(o => o.Key, o => o.Value);
            // Filter group status init
            Hoteldata.FilterGroupStatus = (from grSt in _context.tblGroupStatus
                                           from grp in Group
                                           where grp.StatusID == grSt.StatusID
                                           group grSt by new { grSt.StatusID, grSt.StatusDesc } into grp
                                           orderby grp.Key.StatusID
                                           select new { Key = grp.Key.StatusID, Value = grp.Key.StatusDesc }).ToDictionary(o => o.Key, o => o.Value);
            // pay method init
            Hoteldata.PayMethod = (from card in _context.tblCards
                                   from cardtype in _context.tblCardTypes
                                   where card.CardTypeID == cardtype.CardTypeID
                                   && card.Active == true
                                   select new { Key = card.CardID, Value = cardtype.CardTypeCode }).ToDictionary(o => o.Key, o => o.Value);
            // vendor status init
            Hoteldata.VendorStatus = (from vnSt in _context.tblVConfirmStatus
                                      where vnSt.Active == true
                                      orderby vnSt.StatusID
                                      select new { Key = vnSt.StatusID, Value = vnSt.StatusDesc }).ToDictionary(o => o.Key, o => o.Value);
            // Filter vendor status init
            Hoteldata.FilterVendorStatus = (from vnSt in _context.tblVConfirmStatus
                                            from grp in Group
                                            from vcnf in Vconfirm
                                            where vcnf.GroupID == grp.GroupID
                                            && vcnf.StatusID == vnSt.StatusID
                                            && vnSt.Active == true
                                            group vnSt by new { vnSt.StatusID, vnSt.StatusDesc } into grp
                                            orderby grp.Key.StatusID
                                            select new { Key = grp.Key.StatusID, Value = grp.Key.StatusDesc }).ToDictionary(o => o.Key, o => o.Value);

            // Nationaity init
            Hoteldata.SearchNationality = (from ctr in _context.tblCountries
                                           where ctr.Active == true
                                           select new { Key = ctr.CountryID, Value = ctr.Nationality }).ToDictionary(o => o.Key, o => o.Value);

            // Arrival City init
            var City = _context.tblCities.Where(city => city.Active == true && (city.CountryID == 1 || city.CountryID == 7)).OrderBy(city => city.City).ToList();
            foreach (var city in City)
            {
                Hoteldata.SearchCity.Add(city.CityID, city.City);
            }
            //Day of Arrival init
            Hoteldata.DayofArrival = new Dictionary<int, string>
                                    {
                                        {1, "Sunday"},
                                        {2, "Monday"}, 
                                        {3, "Tuesday"}, 
                                        {4, "Wednesday"},
                                        {5, "Thursday"},
                                        {6, "Friday"},
                                        {7, "Saturday"},
                                    };
            //Filter Day of Arrival init
            var Days = (from vndconf in Vconfirm
                        from grp in Group
                        where grp.GroupID == vndconf.GroupID
                        group vndconf by new { vndconf.ArrivalDate } into grp
                        orderby grp.Key.ArrivalDate
                        select (int)SqlFunctions.DatePart("weekday", grp.Key.ArrivalDate)).ToList();
            Hoteldata.FilterDayofArrival = (from Day in Hoteldata.DayofArrival
                                            from grp in Days
                                            where Day.Key == grp
                                            group Day by new { Day.Key, Day.Value } into grpDay
                                            orderby grpDay.Key.Key
                                            select new { Key = grpDay.Key.Key, Value = grpDay.Key.Value }).ToDictionary(o => o.Key, o => o.Value);
            //Month of Arrival init
            Hoteldata.MonthofArrival = new Dictionary<int, string>
                                    {
                                        {1, "January"},
                                        {2, "February"}, 
                                        {3, "March"}, 
                                        {4, "April"},
                                        {5, "May"},
                                        {6, "June"},
                                        {7, "July"},
                                        {8, "August"},
                                        {9, "September"},
                                        {10, "October"},
                                        {11, "November"},
                                        {12, "December"},
                                    };
            //Filter Day of Arrival init
            var Months = (from vndconf in Vconfirm
                          from grp in Group
                          where grp.GroupID == vndconf.GroupID
                          group vndconf by new { vndconf.ArrivalDate } into grp
                          orderby grp.Key.ArrivalDate
                          select (int)SqlFunctions.DatePart("Month", grp.Key.ArrivalDate)).ToList();
            Hoteldata.FilterMonthofArrival = (from Month in Hoteldata.MonthofArrival
                                              from grp in Months
                                              where Month.Key == grp
                                              group Month by new { Month.Key, Month.Value } into grpMonth
                                              orderby grpMonth.Key.Key
                                              select new { Key = grpMonth.Key.Key, Value = grpMonth.Key.Value }).ToDictionary(o => o.Key, o => o.Value);
            // Arrival City init
            Hoteldata.ArrivalCity = (from vndconf in _context.tblVendorConfirms
                                     where vndconf.ArrivalCity != null
                                     && vndconf.ArrivalCity.Length > 2
                                     group vndconf by new { vndconf.ArrivalCity } into grp
                                     orderby grp.Key.ArrivalCity
                                     select grp.Key.ArrivalCity).ToList();
            //Filter Arrival City init
            Hoteldata.FilterArrivalCity = (from vndconf in Vconfirm
                                           from grp in Group
                                           where vndconf.ArrivalCity != null
                                           && vndconf.ArrivalCity.Length > 2
                                           && grp.GroupID == vndconf.GroupID
                                           group vndconf by new { vndconf.ArrivalCity } into grp
                                           orderby grp.Key.ArrivalCity
                                           select grp.Key.ArrivalCity).ToList();
            // Estimated Number of Rooms init
            Hoteldata.EstRoomNumber = (from vndconf in _context.tblVendorConfirms
                                       where vndconf.Rooms != null
                                       && vndconf.Rooms > 0
                                       group vndconf by new { vndconf.Rooms } into grp
                                       orderby grp.Key.Rooms
                                       select grp.Key.Rooms).ToList();
            //Filter Estimated Number of Rooms init
            Hoteldata.FilterEstRoomNumber = (from vndconf in Vconfirm
                                             from grp in Group
                                             where vndconf.Rooms != null
                                             && vndconf.Rooms > 0
                                             && grp.GroupID == vndconf.GroupID
                                             group vndconf by new { vndconf.Rooms } into grp
                                             orderby grp.Key.Rooms
                                             select grp.Key.Rooms).ToList();
            // Group Code init
            Hoteldata.GroupCode = (from grp in _context.tblGroups
                                   where grp.GroupCode != null
                                   orderby grp.GroupCode
                                   select new { Key = grp.GroupID, Value = grp.GroupCode }).ToDictionary(o => o.Key, o => o.Value);
            //Filter Group Code init
            Hoteldata.FilterGroupCode = (from grp in Group
                                         where grp.GroupCode != null
                                         orderby grp.GroupCode
                                         select new { Key = grp.GroupID, Value = grp.GroupCode }).ToDictionary(o => o.Key, o => o.Value);
            // Group Name init
            Hoteldata.GroupName = (from grp in _context.tblGroups
                                   where grp.GroupName != null
                                   orderby grp.GroupName
                                   select new { Key = grp.GroupID, Value = grp.GroupName }).ToDictionary(o => o.Key, o => o.Value);
            //Filter Group Name init
            Hoteldata.FilterGroupName = (from grp in Group
                                         where grp.GroupName != null
                                         orderby grp.GroupName
                                         select new { Key = grp.GroupID, Value = grp.GroupName }).ToDictionary(o => o.Key, o => o.Value);
            // Customer Code init
            Hoteldata.CustomerCode = (from cust in _context.tblCustomers
                                      where cust.Active == true
                                      && cust.CustomerCode != null
                                      && (from grp in _context.tblGroups select grp.CustomerID).Contains(cust.CustomerID)
                                      group cust by new { cust.CustomerID, cust.CustomerCode } into grp
                                      orderby grp.Key.CustomerCode
                                      select new { Key = grp.Key.CustomerID, Value = grp.Key.CustomerCode }).ToDictionary(o => o.Key, o => o.Value);
            //Filter Customer Code init
            Hoteldata.FilterCustomerCode = (from cust in _context.tblCustomers
                                            where cust.Active == true
                                            && cust.CustomerCode != null
                                            && (from grp in Group select grp.CustomerID).Contains(cust.CustomerID)
                                            group cust by new { cust.CustomerID, cust.CustomerCode } into grp
                                            orderby grp.Key.CustomerCode
                                            select new { Key = grp.Key.CustomerID, Value = grp.Key.CustomerCode }).ToDictionary(o => o.Key, o => o.Value);

            // Vendor Name init
            Hoteldata.VendorName = (from vnd in _context.tblVendors
                                    where vnd.VendorTypeID == 1
                                    && vnd.Active == true
                                    && vnd.VendorName != null
                                    && vnd.VendorName.Length > 5
                                    && (from vndconf in _context.tblVendorConfirms select vndconf.VendorID).Contains(vnd.VendorID)
                                    group vnd by new { vnd.VendorID, vnd.VendorName } into grp
                                    orderby grp.Key.VendorName
                                    select new { Key = grp.Key.VendorID, Value = grp.Key.VendorName }).ToDictionary(o => o.Key, o => o.Value);
            //Filter Vendor Name init
            Hoteldata.FilterVendorName = (from vnd in _context.tblVendors
                                          where vnd.Active == true
                                          && vnd.VendorName != null
                                          && vnd.VendorTypeID == 1
                                          && (from vndconf in Vconfirm from grp in Group where vndconf.GroupID == grp.GroupID select vndconf.VendorID).Contains(vnd.VendorID)
                                          group vnd by new { vnd.VendorID, vnd.VendorName } into grp
                                          orderby grp.Key.VendorName
                                          select new { Key = grp.Key.VendorID, Value = grp.Key.VendorName }).ToDictionary(o => o.Key, o => o.Value);

            // Vendor City init
            Hoteldata.VendorCity = (from vnd in _context.tblVendors
                                    where vnd.Active == true
                                    && vnd.VendorTypeID == 1
                                    && vnd.City != null
                                    && vnd.City.Length > 2
                                    && (from vndconf in Vconfirm select vndconf.VendorID).Contains(vnd.VendorID)
                                    group vnd by new { vnd.City } into grp
                                    orderby grp.Key.City
                                    select grp.Key.City).ToList();
            // Filter Vendor City init
            Hoteldata.FilterVendorCity = (from vnd in _context.tblVendors
                                          where vnd.Active == true
                                          && vnd.VendorTypeID == 1
                                          && vnd.City != null
                                          && vnd.City.Length > 2
                                          && (from vndconf in Vconfirm from grp in Group where vndconf.GroupID == grp.GroupID select vndconf.VendorID).Contains(vnd.VendorID)
                                          group vnd by new { vnd.City } into grp
                                          orderby grp.Key.City
                                          select grp.Key.City).ToList();
        }

        private void InitOperationRoomGridBData(OperationRoomGridBData Roomdata, string GroupCode, int GroupID)
        {
            Roomdata.Customer = new Dictionary<int, string>();
            Roomdata.Roomtype = new Dictionary<int, string>();
            Roomdata.Title = new List<TitleInfo>();
            tblGroup Group = null;
            if (GroupCode != null)
                Group = _context.tblGroups.Where(gr => gr.GroupCode == GroupCode).SingleOrDefault();
            else
                Group = _context.tblGroups.Where(gr => gr.GroupID == GroupID).SingleOrDefault();
            if (Group != null)
            {
                if (Group.QuotaID != null && Group.ArrivalDate != null)
                {
                    var CustId = _context.tblGroups.Where(grp => grp.QuotaID == Group.QuotaID && grp.ArrivalDate == Group.ArrivalDate).Select(grp => grp.CustomerID).ToList();
                    // Customer init
                    var customer = _context.tblCustomers.Where(obj => obj.Active == true && CustId.Contains(obj.CustomerID)).OrderBy(obj => obj.OrganizationName).Select(obj => new { CustId = obj.CustomerID, customer = obj.OrganizationName }).ToList();
                    foreach (var cust in customer)
                    {
                        if (cust.customer != null)
                            Roomdata.Customer.Add(cust.CustId, cust.customer);
                    }
                }
            }
            // Room Type init
            var service = _context.tblServices.Where(obj => obj.ServiceTypeID == 1 && obj.ServiceID != 103 && obj.Active == true).Select(obj => new { ServId = obj.ServiceID, RoomType = obj.ServiceCode }).ToList();
            foreach (var serv in service)
            {
                Roomdata.Roomtype.Add(serv.ServId, serv.RoomType);
            }
            // Pax init, room pax init, room type init
            Roomdata.Title = (from title in _context.tblTitles
                              from serv in _context.tblServices
                              where title.ServiceID == serv.ServiceID
                              && serv.Active == true
                              && serv.ServiceTypeID == 1
                              select new TitleInfo { ServiceCode = serv.ServiceCode, Title = title.Title }).ToList();
        }
        private void InitOperationRoomGridBData(OperationRoomGridBData Roomdata, string GroupCode, int GroupID, ref List<OperationRoomGirGridRowBData> GirRow)
        {
            Roomdata.Customer = new Dictionary<int, string>();
            Roomdata.Roomtype = new Dictionary<int, string>();
            Roomdata.Title = new List<TitleInfo>();
            tblGroup Group = null;
            if (GroupCode != null)
                Group = _context.tblGroups.Where(gr => gr.GroupCode == GroupCode).SingleOrDefault();
            else
                Group = _context.tblGroups.Where(gr => gr.GroupID == GroupID).SingleOrDefault();
            if (Group != null)
            {
                if (Group.QuotaID != null && Group.ArrivalDate != null)
                {
                    var customer = (from cus in _context.tblCustomers
                                    from GirDet in _context.tblGirGroupDetails
                                    where cus.CustomerID == GirDet.CustomerID 
                                    && cus.Active == true
                                    && GirDet.GroupID == Group.GroupID
                                    orderby cus.OrganizationName
                                    select new
                                    {
                                        CustId = cus.CustomerID,
                                        customer = cus.OrganizationName,
                                        GroupID = GirDet.GroupID,
                                        PerPrice = GirDet.PricePerPerson,
                                        FullBoardPrice = GirDet.PriceFullBoard,
                                        SingleSupPrice = GirDet.PriceSingleSupp,
                                        PerPriceCad = GirDet.PricePerPersonCad,
                                        FullBoardPriceCad = GirDet.PriceFullBoardCad,
                                        SingleSupPriceCad = GirDet.PriceSingleSuppCad,
                                    }).ToList();
                    Roomdata.Customer = (from cus in customer select new { Key = cus.CustId, Value = cus.customer }).ToDictionary(o => o.Key, o => o.Value);
                    foreach (var girrow in GirRow)
                    {
                        var EntCust = customer.Where(cust => cust.customer == girrow.CustomerName).FirstOrDefault();
                        if (EntCust != null)
                        {
                            girrow.GroupID = EntCust.GroupID;
                            girrow.PerPrice = EntCust.PerPrice;
                            girrow.FullBoardPrice = EntCust.FullBoardPrice;
                            girrow.SingleSupPrice = EntCust.SingleSupPrice;
                            girrow.PerPriceCad = EntCust.PerPriceCad;
                            girrow.FullBoardPriceCad = EntCust.FullBoardPriceCad;
                            girrow.SingleSupPriceCad = EntCust.SingleSupPriceCad;
                        }
                    }
                }
            }
            // Room Type init
            var service = _context.tblServices.Where(obj => obj.ServiceTypeID == 1 && obj.ServiceID != 103 && obj.Active == true).Select(obj => new { ServId = obj.ServiceID, RoomType = obj.ServiceCode }).ToList();
            foreach (var serv in service)
            {
                Roomdata.Roomtype.Add(serv.ServId, serv.RoomType);
            }
            // Pax init, room pax init, room type init
            Roomdata.Title = (from title in _context.tblTitles
                              from serv in _context.tblServices
                              where title.ServiceID == serv.ServiceID
                              && serv.Active == true
                              && serv.ServiceTypeID == 1
                              select new TitleInfo { ServiceCode = serv.ServiceCode, Title = title.Title }).ToList();
        }
        private void OperationAttractionsFiltersInit(ref IQueryable<tblGroup> FilterGroup, ref IQueryable<tblVendor> FilterVendor,ref IQueryable<tblAttractionsConfirm> FilterAttractionsConfirm,ref IQueryable<tblRestaurantsConfirm> FilterRestaurantsConfirm, OperationAttractionsFilterBData Data)
        {
            // filtering Attractions Group Code
            if (Data.FilterAttractionsGroupCodeVal != null)
                FilterGroup = FilterGroup.Where(grp => Data.FilterAttractionsGroupCodeVal.Contains(grp.GroupID));
            // filtering Attractions Group Name
            if (Data.FilterAttractionsGroupNameVal != null)
                FilterGroup = FilterGroup.Where(grp => Data.FilterAttractionsGroupNameVal.Contains(grp.GroupID));
            // filtering Customer Code
            if (Data.FilterAttractionsCustomerCodeVal != null)
                FilterGroup = FilterGroup.Where(grp => Data.FilterAttractionsCustomerCodeVal.Contains(grp.CustomerID));
            // filtering Status
            if (Data.FilterAttractionsStatusVal != null)
            {
                FilterAttractionsConfirm = FilterAttractionsConfirm.Where(vconf => Data.FilterAttractionsStatusVal.Contains(vconf.StatusID));
                FilterRestaurantsConfirm = FilterRestaurantsConfirm.Where(vconf => Data.FilterAttractionsStatusVal.Contains(vconf.StatusID));
            }
            // filtering Vendor Name
            if (Data.FilterAttractionsVendorNameVal != null)
            {
                FilterAttractionsConfirm = FilterAttractionsConfirm.Where(vconf => Data.FilterAttractionsVendorNameVal.Contains(vconf.VendorID));
                FilterRestaurantsConfirm = FilterRestaurantsConfirm.Where(vconf => Data.FilterAttractionsVendorNameVal.Contains(vconf.VendorID));
            }
            // filtering Vendor City
            if (Data.FilterAttractionsVendorCityVal != null)
            {
                var VendorIDs = FilterVendor.Where(vnd => Data.FilterAttractionsVendorCityVal.Contains(vnd.City)).Select(vnd => vnd.VendorID);
                FilterAttractionsConfirm = FilterAttractionsConfirm.Where(vconf => VendorIDs.Contains(vconf.VendorID));
                FilterRestaurantsConfirm = FilterRestaurantsConfirm.Where(vconf => VendorIDs.Contains(vconf.VendorID));
            }
            // filtering Restaurant Type
            if (Data.FilterAttractionsRestaurantTypeVal != null)
            {
                var VendorIDs = FilterVendor.Where(vnd => vnd.VendorTypeID == 2).Select(vnd => vnd.VendorID);
                FilterAttractionsConfirm = FilterAttractionsConfirm.Where(vconf => VendorIDs.Contains(vconf.VendorID));
                FilterRestaurantsConfirm = FilterRestaurantsConfirm.Where(vconf => Data.FilterAttractionsRestaurantTypeVal.Contains(vconf.Category));
            }
            // filtering Vendor Type
            if (Data.FilterAttractionsVendorTypeVal != null)
            {
                var VendorIDs = FilterVendor.Where(vnd => Data.FilterAttractionsVendorTypeVal.Contains(vnd.VendorTypeID)).Select(vnd => vnd.VendorID);
                FilterAttractionsConfirm = FilterAttractionsConfirm.Where(vconf => VendorIDs.Contains(vconf.VendorID));
                FilterRestaurantsConfirm = FilterRestaurantsConfirm.Where(vconf => VendorIDs.Contains(vconf.VendorID));
            }
        }
        private List<OperationMiscGridRowBData> InitMiscGridBData(int PageNum, IQueryable<tblGroup> Group, IQueryable<tblCustomer> Customer, IQueryable<tblVendor> Vendor, IQueryable<tblMiscConfirm> MiscConfirm, List<string> UserRegions, string UserName, ref int MiscCount)
        {
            List<OperationMiscGridRowBData> Rows = new List<OperationMiscGridRowBData>();
            // Employee
            var EmpID = _context.Users.Where(usr => usr.UserName == UserName).Select(usr => usr.EmployeeID).SingleOrDefault();
            var GroupIds = Group.Select(grp => grp.GroupID).ToList();
            var AllGroup = Group.ToList();
            var GrpRooms = _context.tblGroupRooms.Where(GrR => GroupIds.Contains(GrR.GroupID)).GroupBy(GrR => GrR.GroupID).Select(GrR => new { GrID = GrR.Key, Pax = (short)GrR.Sum(rm => rm.NoOfPerson) }).ToList();
            MiscCount = (from Grp in Group
                         from Cust in Customer
                         from MiscConf in MiscConfirm
                         from Vnd in Vendor
                         from VndType in _context.tblVendorTypes
                         from VndStatus in _context.tblVConfirmStatus
                         from quota in _context.tblQuotations
                         where Grp.QuotaID == quota.QuotaID && UserRegions.Contains(quota.Region)
                         && MiscConf.GroupID == Grp.GroupID
                         && Cust.CustomerID == Grp.CustomerID && Cust.Active == true
                         && Vnd.VendorID == MiscConf.VendorID && Vnd.Active == true
                         && Vnd.VendorTypeID == VndType.VendorTypeID
                         && MiscConf.StatusID == VndStatus.StatusID && VndStatus.Active == true
                         select MiscConf.GroupID).Count();
            Rows = (from Grp in Group
                    from Cust in Customer
                    from MiscConf in MiscConfirm
                    from Vnd in Vendor
                    from VndType in _context.tblVendorTypes
                    from VndStatus in _context.tblVConfirmStatus
                    from quota in _context.tblQuotations
                    where Grp.QuotaID == quota.QuotaID && UserRegions.Contains(quota.Region)
                    && MiscConf.GroupID == Grp.GroupID
                    && Cust.CustomerID == Grp.CustomerID && Cust.Active == true
                    && Vnd.VendorID == MiscConf.VendorID && Vnd.Active == true
                    && Vnd.VendorTypeID == VndType.VendorTypeID
                    && MiscConf.StatusID == VndStatus.StatusID && VndStatus.Active == true
                    orderby MiscConf.StartDate
                    select new OperationMiscGridRowBData()
                    {
                        GroupID = MiscConf.GroupID,
                        VendorSelStatus = VndStatus.StatusDesc,
                        VendorID = MiscConf.VendorID,
                        StartDate = MiscConf.StartDate,
                        StatusID = MiscConf.StatusID,
                        EmployeeID = _context.tblEmployees.Any(emp => emp.EmployeeID == MiscConf.EmployeeID) ? MiscConf.EmployeeID : EmpID,
                        QuotaID = Grp.QuotaID,
                        Time = MiscConf.Time,
                        UnitPrice = MiscConf.UnitPrice,
                        UnitPricePG = MiscConf.UnitPricePerGroup,
                        ServiceDetID = MiscConf.ServiceDetID,
                        VendorName = Vnd.VendorName,
                        VendorAddress = Vnd.Address,
                        VendorPhone = Vnd.PhoneNumber,
                        VendorEmail = Vnd.EmailName,
                        VendorContactName = Vnd.ContactName,
                        VendorCity = Vnd.City,
                        MiscGroupContractPath = MiscConf.MiscConfirmFile,
                        GroupCode = Grp.GroupCode,
                        GroupName = Grp.GroupName,
                        CustomerID = Grp.CustomerID,
                        Customer = Cust.OrganizationName,
                        EstNumOfPerson = Grp.NoOfPerson,
                        NumOfPerson = MiscConf.Pax,
                        QuotaVendorName = MiscConf.QuotaVendorDesc,
                        QuotaCurrency = MiscConf.QuotaCurr,
                        QuotaRate = MiscConf.QuotaRate,
                        QuotaGrpRate = MiscConf.QuotaPerGroupRate,
                        Plane = MiscConf.PlaneFlag,
                        IsComp = MiscConf.IsComp,
                        Notes = MiscConf.Notes,
                        FirstPayAmt = MiscConf.FirstPayment,
                        FirstPayMethod = MiscConf.FirstPaymentMethod,
                        FirstPayDate = MiscConf.FirstPaymentDate,
                        SecondPayAmt = MiscConf.SecondPayment,
                        SecondPayMethod = MiscConf.SecondPaymentMethod,
                        SecondPayDate = MiscConf.SecondPaymentDate,
                        ThirdPayAmt = MiscConf.ThirdPayment,
                        ThirdPayMethod = MiscConf.ThirdPaymentMethod,
                        ThirdPayDate = MiscConf.ThirdPaymentDate,
                    }).Skip((PageNum - 1) * OperationMiscGridBData.TakeCount).Take(OperationMiscGridBData.TakeCount).ToList();
            foreach (var row in Rows)
            {
                short Pax = GrpRooms.Where(Rm => Rm.GrID == row.GroupID).Select(Rm => Rm.Pax).SingleOrDefault();
                if (row.NumOfPerson == null || row.NumOfPerson == 0)
                    row.NumOfPerson = Pax == 0 ? AllGroup.Where(grp => grp.GroupID == row.GroupID).Select(grp => grp.NoOfPerson).SingleOrDefault() : Pax;
                else if (row.NumOfPerson > 0 && Pax > 0 && row.NumOfPerson != Pax)
                    row.NumOfPerson = Pax;
            }
            return Rows;
        }
        private void OperationMiscFiltersInit(ref IQueryable<tblGroup> FilterGroup, ref IQueryable<tblVendor> FilterVendor, ref IQueryable<tblMiscConfirm> FilterMiscConfirm, OperationMiscFilterBData Data)
        {
            // filtering Misc Group Code
            if (Data.FilterMiscGroupCodeVal != null)
                FilterGroup = FilterGroup.Where(grp => Data.FilterMiscGroupCodeVal.Contains(grp.GroupID));
            // filtering Misc Group Name
            if (Data.FilterMiscGroupNameVal != null)
                FilterGroup = FilterGroup.Where(grp => Data.FilterMiscGroupNameVal.Contains(grp.GroupID));
            // filtering Customer Code
            if (Data.FilterMiscCustomerCodeVal != null)
                FilterGroup = FilterGroup.Where(grp => Data.FilterMiscCustomerCodeVal.Contains(grp.CustomerID));
            // filtering Status
            if (Data.FilterMiscStatusVal != null)
                FilterMiscConfirm = FilterMiscConfirm.Where(mconf => Data.FilterMiscStatusVal.Contains(mconf.StatusID));
            // filtering Vendor Name
            if (Data.FilterMiscVendorNameVal != null)
                FilterMiscConfirm = FilterMiscConfirm.Where(mconf => Data.FilterMiscVendorNameVal.Contains(mconf.VendorID));
            // filtering Vendor City
            if (Data.FilterMiscVendorCityVal != null)
            {
                var VendorIDs = FilterVendor.Where(vnd => Data.FilterMiscVendorCityVal.Contains(vnd.City)).Select(vnd => vnd.VendorID);
                FilterMiscConfirm = FilterMiscConfirm.Where(mconf => VendorIDs.Contains(mconf.VendorID));
            }
        }
        private List<OperationAttractionsGridRowBData> InitAttractionsGridBData(int PageNum, IQueryable<tblGroup> Group, IQueryable<tblCustomer> Customer, IQueryable<tblRestaurantsConfirm> RestaurantsConfirm, IQueryable<tblVendor> Vendor, IQueryable<tblAttractionsConfirm> AttractionsConfirm, List<string> UserRegions, string UserName, ref int Count)
        {
            List<OperationAttractionsGridRowBData> Rows = new List<OperationAttractionsGridRowBData>();
            // Employee
            var EmpID = _context.Users.Where(usr => usr.UserName == UserName).Select(usr => usr.EmployeeID).SingleOrDefault();
            var GroupIds = Group.Select(grp=>grp.GroupID).ToList();
            var AllGroup = Group.ToList();
            var GrpRooms = _context.tblGroupRooms.Where(GrR => GroupIds.Contains(GrR.GroupID)).GroupBy(GrR => GrR.GroupID).Select(GrR => new { GrID = GrR.Key, Pax = (short)GrR.Sum(rm=>rm.NoOfPerson)}).ToList();
            var attcount = (from Grp in Group
                            from Cust in Customer
                            from AttractionsConf in AttractionsConfirm
                            from Vnd in Vendor
                            from VndType in _context.tblVendorTypes
                            from VndStatus in _context.tblVConfirmStatus
                            from quota in _context.tblQuotations
                            where Grp.QuotaID == quota.QuotaID && UserRegions.Contains(quota.Region)
                            && AttractionsConf.GroupID == Grp.GroupID
                            && Cust.CustomerID == Grp.CustomerID && Cust.Active == true
                            && Vnd.VendorID == AttractionsConf.VendorID && Vnd.Active == true
                            && Vnd.VendorTypeID == VndType.VendorTypeID
                            && AttractionsConf.StatusID == VndStatus.StatusID && VndStatus.Active == true
                            select AttractionsConf.GroupID).Count();
            var restcount =  (from Grp in Group
                             from Cust in Customer
                             from RestaurantsConf in RestaurantsConfirm
                             from Vnd in Vendor
                             from VndType in _context.tblVendorTypes
                             from VndStatus in _context.tblVConfirmStatus
                             from quota in _context.tblQuotations
                             where Grp.QuotaID == quota.QuotaID && UserRegions.Contains(quota.Region)
                             && RestaurantsConf.GroupID == Grp.GroupID
                             && Cust.CustomerID == Grp.CustomerID && Cust.Active == true
                             && Vnd.VendorID == RestaurantsConf.VendorID && Vnd.Active == true
                             && Vnd.VendorTypeID == VndType.VendorTypeID
                             && RestaurantsConf.StatusID == VndStatus.StatusID && VndStatus.Active == true
                             select RestaurantsConf.GroupID).Count();
            Count = restcount + attcount;
            var AttrRestGrid = (from Grp in Group
                                  from Cust in Customer
                                  from AttractionsConf in AttractionsConfirm
                                  from Vnd in Vendor
                                  from VndType in _context.tblVendorTypes
                                  from VndStatus in _context.tblVConfirmStatus
                                  from quota in _context.tblQuotations    
                                  where Grp.QuotaID == quota.QuotaID && UserRegions.Contains(quota.Region)
                                  && AttractionsConf.GroupID == Grp.GroupID
                                  && Cust.CustomerID == Grp.CustomerID && Cust.Active == true
                                  && Vnd.VendorID == AttractionsConf.VendorID && Vnd.Active == true
                                  && Vnd.VendorTypeID == VndType.VendorTypeID
                                  && AttractionsConf.StatusID == VndStatus.StatusID && VndStatus.Active == true
                                  select new OperationAttractionsGridRowBData()
                                  {
                                      GroupID = AttractionsConf.GroupID,
                                      VendorID = AttractionsConf.VendorID,
                                      StartDate = AttractionsConf.StartDate,
                                      FinishDate = AttractionsConf.FinishDate,
                                      ConfirmDate = AttractionsConf.ConfirmDate,
                                      StatusID = AttractionsConf.StatusID,
                                      ServiceID = null,
                                      VendorSelStatus = VndStatus.StatusDesc,
                                      RestSelService = null,
                                      IsGuideInvoice = AttractionsConf.IsGuideInvoice,
                                      GuideInvoicePrice = AttractionsConf.GuideInvoicePrice,
                                      IsInvoice = AttractionsConf.IsInvoice,
                                      InvoicePrice = AttractionsConf.InvoicePrice,
                                      EmployeeID = _context.tblEmployees.Any(emp => emp.EmployeeID == AttractionsConf.EmployeeID) ? AttractionsConf.EmployeeID : EmpID,
                                      QuotaID = Grp.QuotaID,
                                      Category = VndType.VendorTypeCode,
                                      Type = null,
                                      EstNumOfPerson = Grp.NoOfPerson,
                                      Done = AttractionsConf.Done,
                                      Time = AttractionsConf.Time,
                                      VendorName = Vnd.VendorName,
                                      VendorAddress = Vnd.Address,
                                      VendorPhone = Vnd.PhoneNumber,
                                      VendorEmail = Vnd.EmailName,
                                      VendorContactName = Vnd.ContactName,
                                      VendorCity = Vnd.City,
                                      AttractionsGroupContractPath = AttractionsConf.AttractionsConfirmFile,
                                      GroupCode = Grp.GroupCode,
                                      GroupName = Grp.GroupName,
                                      NumOfPerson = AttractionsConf.Pax,
                                      CustomerID = Grp.CustomerID,
                                      Customer = Cust.OrganizationName,
                                      Deposit = AttractionsConf.Deposit,
                                      DepositAmtPaid = AttractionsConf.DepositAmtPaid,
                                      UnitRate = AttractionsConf.UnitRate,
                                      DepositDate = AttractionsConf.DepositDate,
                                      CCChargeAmt = AttractionsConf.CCChargeAmt,
                                      CCMemo = AttractionsConf.CCMemo,
                                      FinalPayment = AttractionsConf.FinalPayment,
                                      FirstPayAmt = AttractionsConf.FirstPayment,
                                      FirstPayMethod = AttractionsConf.FirstPaymentMethod,
                                      FirstPayDate = AttractionsConf.FirstPaymentDate,
                                      SecondPayAmt = AttractionsConf.SecondPayment,
                                      SecondPayMethod = AttractionsConf.SecondPaymentMethod,
                                      SecondPayDate = AttractionsConf.SecondPaymentDate,
                                      ThirdPayAmt = AttractionsConf.ThirdPayment,
                                      ThirdPayMethod = AttractionsConf.ThirdPaymentMethod,
                                      ThirdPayDate = AttractionsConf.ThirdPaymentDate,
                                      QuotaVendorName = AttractionsConf.QuotaVendorDesc,
                                      QuotaCurrency = AttractionsConf.QuotaCurr,
                                      QuotaRate = AttractionsConf.QuotaRate,
                                  }).Union(
                                  from Grp in Group
                                  from Cust in Customer
                                  from RestaurantsConf in RestaurantsConfirm
                                  from Vnd in Vendor
                                  from VndType in _context.tblVendorTypes
                                  from VndStatus in _context.tblVConfirmStatus
                                  from quota in _context.tblQuotations   
                                  where Grp.QuotaID == quota.QuotaID && UserRegions.Contains(quota.Region)
                                  && RestaurantsConf.GroupID == Grp.GroupID
                                  && Cust.CustomerID == Grp.CustomerID && Cust.Active == true
                                  && Vnd.VendorID == RestaurantsConf.VendorID && Vnd.Active == true
                                  && Vnd.VendorTypeID == VndType.VendorTypeID
                                  && RestaurantsConf.StatusID == VndStatus.StatusID && VndStatus.Active == true
                                  select new OperationAttractionsGridRowBData()
                                  {
                                      GroupID = RestaurantsConf.GroupID,
                                      VendorID = RestaurantsConf.VendorID,
                                      StartDate = RestaurantsConf.StartDate,
                                      FinishDate = RestaurantsConf.FinishDate,
                                      ConfirmDate = RestaurantsConf.ConfirmDate,
                                      StatusID = RestaurantsConf.StatusID,
                                      ServiceID = RestaurantsConf.ServiceID,
                                      VendorSelStatus = VndStatus.StatusDesc,
                                      RestSelService = _context.tblServices.Any(ser => ser.ServiceID == RestaurantsConf.ServiceID) ? (from Service in _context.tblServices
                                                                                                                                      from ServiceTypes in _context.tblServiceTypes
                                                                                                                                      where Service.ServiceID == RestaurantsConf.ServiceID
                                                                                                                                      && Service.ServiceTypeID == ServiceTypes.ServiceTypeID
                                                                                                                                      && Service.Active == true
                                                                                                                                      && ServiceTypes.Active == true
                                                                                                                                      orderby ServiceTypes.ServiceTypeCode
                                                                                                                                      select ServiceTypes.ServiceTypeCode + " - " + Service.ServiceCode).FirstOrDefault() : null,
                                      IsGuideInvoice = RestaurantsConf.IsGuideInvoice,
                                      GuideInvoicePrice = RestaurantsConf.GuideInvoicePrice,
                                      IsInvoice = RestaurantsConf.IsInvoice,
                                      InvoicePrice = RestaurantsConf.InvoicePrice,
                                      EmployeeID = _context.tblEmployees.Any(emp => emp.EmployeeID == RestaurantsConf.EmployeeID) ? RestaurantsConf.EmployeeID : EmpID,
                                      QuotaID = Grp.QuotaID,
                                      Category = VndType.VendorTypeCode,
                                      Type = RestaurantsConf.Category,
                                      EstNumOfPerson = Grp.NoOfPerson,
                                      Done = RestaurantsConf.Done,
                                      Time = RestaurantsConf.Time,
                                      VendorName = Vnd.VendorName,
                                      VendorAddress = Vnd.Address,
                                      VendorPhone = Vnd.PhoneNumber,
                                      VendorEmail = Vnd.EmailName,
                                      VendorContactName = Vnd.ContactName,
                                      VendorCity = Vnd.City,
                                      AttractionsGroupContractPath = RestaurantsConf.RestaurantsConfirmFile,
                                      GroupCode = Grp.GroupCode,
                                      GroupName = Grp.GroupName,
                                      NumOfPerson = RestaurantsConf.Pax,
                                      CustomerID = Grp.CustomerID,
                                      Customer = Cust.OrganizationName,
                                      Deposit = RestaurantsConf.Deposit,
                                      DepositAmtPaid = RestaurantsConf.DepositAmtPaid,
                                      UnitRate = RestaurantsConf.UnitRate,
                                      DepositDate = RestaurantsConf.DepositDate,
                                      CCChargeAmt = RestaurantsConf.CCChargeAmt,
                                      CCMemo = RestaurantsConf.CCMemo,
                                      FinalPayment = RestaurantsConf.FinalPayment,
                                      FirstPayAmt = RestaurantsConf.FirstPayment,
                                      FirstPayMethod = RestaurantsConf.FirstPaymentMethod,
                                      FirstPayDate = RestaurantsConf.FirstPaymentDate,
                                      SecondPayAmt = RestaurantsConf.SecondPayment,
                                      SecondPayMethod = RestaurantsConf.SecondPaymentMethod,
                                      SecondPayDate = RestaurantsConf.SecondPaymentDate,
                                      ThirdPayAmt = RestaurantsConf.ThirdPayment,
                                      ThirdPayMethod = RestaurantsConf.ThirdPaymentMethod,
                                      ThirdPayDate = RestaurantsConf.ThirdPaymentDate,
                                      QuotaVendorName = RestaurantsConf.QuotaVendorDesc,
                                      QuotaCurrency = RestaurantsConf.QuotaCurr,
                                      QuotaRate = RestaurantsConf.QuotaRate,
                                  });
            Rows.AddRange(AttrRestGrid.OrderBy(row => row.StartDate).Skip((PageNum - 1) * OperationAttractionsGridBData.TakeCount).Take(OperationAttractionsGridBData.TakeCount));
            foreach (var row in Rows)
            {
                short Pax = GrpRooms.Where(Rm=>Rm.GrID == row.GroupID).Select(Rm => Rm.Pax).SingleOrDefault();
                if (row.IsInvoice == false || row.NumOfPerson == null)
                {
                    if (row.NumOfPerson == null || row.NumOfPerson == 0)
                        row.NumOfPerson = Pax == 0 ? AllGroup.Where(grp => grp.GroupID == row.GroupID).Select(grp => grp.NoOfPerson).SingleOrDefault() : Pax;
                    else if (row.NumOfPerson > 0 && Pax > 0 && row.NumOfPerson != Pax)
                        row.NumOfPerson = Pax;
                }
            }
            return Rows;
        }
        private void InitOperationAttractionsGridBData(OperationAttractionsGridBData AttractionsData, IQueryable<tblAttractionsConfirm> Attrconfirm, IQueryable<tblRestaurantsConfirm> Restconfirm, IQueryable<tblGroup> Group, string UserName)
        {
            AttractionsData.VendorInfo = new List<OperationAttractionsVendorInfoBData>();
            AttractionsData.VendorName = new Dictionary<int, string>();
            AttractionsData.GroupCode = new Dictionary<int, string>();
            AttractionsData.Customer = new Dictionary<int, string>();
            AttractionsData.VendorCity = new List<string>();
            AttractionsData.VendorStatus = new Dictionary<int, string>();
            AttractionsData.RestServices = new Dictionary<int, string>();
            AttractionsData.PayMethod = new Dictionary<int, string>();
            AttractionsData.Employee = new Dictionary<int, string>();
            AttractionsData.FilterVendorCity = new List<string>();
            // Employee
            var EmpID = _context.Users.Where(usr => usr.UserName == UserName).Select(usr => usr.EmployeeID).SingleOrDefault();
            var SupEmp = _context.tblSupEmployees.Where(sup => sup.EmployeeID == EmpID).Select(sup => sup.SupervisorID).ToList();
            AttractionsData.Employee = (from user in _context.Users
                                  from emp in _context.tblEmployees
                                  where user.EmployeeID == emp.EmployeeID && emp.Active == true && SupEmp.Contains((int)user.EmployeeID)
                                  orderby emp.FirstName, emp.LastName
                                  select new
                                  {
                                      Key = emp.EmployeeID,
                                      Value = emp.FirstName + " " + emp.LastName,
                                  }).ToDictionary(o => o.Key, o => o.Value);
            // vendor status init
            AttractionsData.VendorStatus = (from vnSt in _context.tblVConfirmStatus
                                      where vnSt.Active == true
                                      orderby vnSt.StatusID
                                      select new { Key = vnSt.StatusID, Value = vnSt.StatusDesc }).ToDictionary(o => o.Key, o => o.Value);
            // Restaurant Service init
            AttractionsData.RestServices = (from Service in _context.tblServices
                                            from ServiceTypes in _context.tblServiceTypes
                                            where ServiceTypes.VendorTypeID == 2
                                            && Service.ServiceTypeID == ServiceTypes.ServiceTypeID
                                            && Service.Active == true
                                            && ServiceTypes.Active == true
                                            orderby ServiceTypes.ServiceTypeCode
                                            select new
                                            {
                                                Key = Service.ServiceID,
                                                Value = ServiceTypes.ServiceTypeCode + " - " + Service.ServiceCode
                                            }).ToDictionary(o => o.Key, o => o.Value);
            // pay method init
            AttractionsData.PayMethod = (from card in _context.tblCards
                                         from cardtype in _context.tblCardTypes
                                         where card.CardTypeID == cardtype.CardTypeID
                                         && card.Active == true
                                         select new { Key = card.CardID, Value = cardtype.CardTypeCode }).ToDictionary(o => o.Key, o => o.Value);
            // Customer Code init
            AttractionsData.Customer = (from cust in _context.tblCustomers
                                            where cust.Active == true
                                            && cust.CustomerCode != null
                                            && (from grp in _context.tblGroups select grp.CustomerID).Contains(cust.CustomerID)
                                            group cust by new { cust.CustomerID, cust.CustomerCode } into grp
                                            orderby grp.Key.CustomerCode
                                            select new { Key = grp.Key.CustomerID, Value = grp.Key.CustomerCode }).ToDictionary(o => o.Key, o => o.Value);
            // Vendor City init
            AttractionsData.VendorCity = (from vnd in _context.tblVendors
                                          where (vnd.VendorTypeID == 2 || vnd.VendorTypeID == 4 || vnd.VendorTypeID == 5)
                                          && vnd.Active == true
                                          && vnd.City != null
                                          && vnd.City.Length > 2
                                          && ((from attrconf in Attrconfirm select attrconf.VendorID).Contains(vnd.VendorID) || (from restconf in Restconfirm select restconf.VendorID).Contains(vnd.VendorID))
                                          group vnd by new { vnd.City } into grp
                                          orderby grp.Key.City
                                          select grp.Key.City).ToList();
            // Vendor Info init
            AttractionsData.VendorInfo = (from vnd in _context.tblVendors
                                          from vndType in _context.tblVendorTypes
                                          where (vnd.VendorTypeID == 2 || vnd.VendorTypeID == 4 || vnd.VendorTypeID == 5)
                                          && vnd.VendorTypeID == vndType.VendorTypeID
                                          && vnd.Active == true
                                          && vnd.VendorName != null
                                          && vnd.VendorName.Length > 5
                                          select new OperationAttractionsVendorInfoBData
                                          {
                                              VendorID = vnd.VendorID,
                                              VendorName = vnd.VendorName,
                                              VendorCity = vnd.City,
                                              VendorAddress = vnd.Address,
                                              VendorContactPerson = vnd.ContactName,
                                              VendorEmail = vnd.EmailNameSales,
                                              VendorPhone = vnd.PhoneSales,
                                              IsFind = vnd.IsFind,
                                              VendorType = vndType.VendorTypeCode,
                                          }).ToList();
            // Vendor Name init
            AttractionsData.VendorName = (from vnd in _context.tblVendors
                                          where (vnd.VendorTypeID == 2 || vnd.VendorTypeID == 4 || vnd.VendorTypeID == 5)
                                          && vnd.Active == true
                                          && vnd.VendorName != null
                                          && vnd.VendorName.Length > 5
                                          && ((from attrconf in _context.tblAttractionsConfirms select attrconf.VendorID).Contains(vnd.VendorID) || (from restconf in _context.tblRestaurantsConfirms select restconf.VendorID).Contains(vnd.VendorID))
                                          group vnd by new { vnd.VendorID, vnd.VendorName } into grp
                                          orderby grp.Key.VendorName
                                          select new { Key = grp.Key.VendorID, Value = grp.Key.VendorName }).ToDictionary(o => o.Key, o => o.Value);
            // Group Code init
            AttractionsData.GroupCode = (from grp in _context.tblGroups
                                         where grp.GroupCode != null
                                         && ((from attr in _context.tblAttractionsConfirms select attr.GroupID).Contains(grp.GroupID) || (from restconf in _context.tblRestaurantsConfirms select restconf.GroupID).Contains(grp.GroupID))
                                         group grp by new { grp.GroupID, grp.GroupCode } into attr
                                         orderby attr.Key.GroupCode
                                         select new { Key = attr.Key.GroupID, Value = attr.Key.GroupCode }).ToDictionary(o => o.Key, o => o.Value);
            //Filter Group Code init
            AttractionsData.FilterGroupCode = (from grp in Group
                                               where grp.GroupCode != null
                                               orderby grp.GroupCode
                                               select new { Key = grp.GroupID, Value = grp.GroupCode }).ToDictionary(o => o.Key, o => o.Value);
            //Filter Group Name init
            AttractionsData.FilterGroupName = (from grp in Group
                                               where grp.GroupName != null
                                               orderby grp.GroupName
                                               select new { Key = grp.GroupID, Value = grp.GroupName }).ToDictionary(o => o.Key, o => o.Value);
            //Filter Customer Code init
            AttractionsData.FilterCustomerCode = (from cust in _context.tblCustomers
                                                  where cust.Active == true
                                                  && cust.OrganizationName != null
                                                  && (from grp in Group select grp.CustomerID).Contains(cust.CustomerID)
                                                  group cust by new { cust.CustomerID, cust.OrganizationName } into grp
                                                  orderby grp.Key.OrganizationName
                                                  select new { Key = grp.Key.CustomerID, Value = grp.Key.OrganizationName }).ToDictionary(o => o.Key, o => o.Value);
            // Filter vendor status init
            var AttStatsus = (from vnSt in _context.tblVConfirmStatus
                              from grp in Group
                              from attrcnf in Attrconfirm
                              where attrcnf.GroupID == grp.GroupID 
                              && attrcnf.StatusID == vnSt.StatusID
                              && vnSt.Active == true
                              group vnSt by new { vnSt.StatusID, vnSt.StatusDesc } into grp
                              orderby grp.Key.StatusID
                              select new { Key = grp.Key.StatusID, Value = grp.Key.StatusDesc }).ToDictionary(o => o.Key, o => o.Value);
            var RestStatsus = (from vnSt in _context.tblVConfirmStatus
                              from grp in Group
                              from restcnf in Restconfirm
                              where restcnf.GroupID == grp.GroupID
                              && restcnf.StatusID == vnSt.StatusID
                              && vnSt.Active == true
                              group vnSt by new { vnSt.StatusID, vnSt.StatusDesc } into grp
                              orderby grp.Key.StatusID
                              select new { Key = grp.Key.StatusID, Value = grp.Key.StatusDesc }).ToDictionary(o => o.Key, o => o.Value);
            foreach(var st in RestStatsus)
            {
                if (!(AttStatsus.Keys.Contains(st.Key)))
                    AttStatsus.Add(st.Key,st.Value);
            }
            AttractionsData.FilterVendorStatus = AttStatsus.OrderBy(st => st.Key).ToDictionary(st=>st.Key,st=>st.Value);
            //Filter Vendor Name init
            var AttName = (from vnd in _context.tblVendors
                           from vnSt in _context.tblVConfirmStatus
                           where vnd.Active == true && vnSt.Active == true
                           && vnd.VendorName != null
                           && (vnd.VendorTypeID == 2 || vnd.VendorTypeID == 4 || vnd.VendorTypeID == 5)
                           && (from attrconf in Attrconfirm from grp in Group where attrconf.GroupID == grp.GroupID && attrconf.StatusID == vnSt.StatusID select attrconf.VendorID).Contains(vnd.VendorID)
                           group vnd by new { vnd.VendorID, vnd.VendorName } into grp
                           orderby grp.Key.VendorName
                           select new { Key = grp.Key.VendorID, Value = grp.Key.VendorName }).ToDictionary(o => o.Key, o => o.Value);
            var RestName = (from vnd in _context.tblVendors
                           from vnSt in _context.tblVConfirmStatus
                           where vnd.Active == true && vnSt.Active == true
                           && vnd.VendorName != null
                           && (vnd.VendorTypeID == 2 || vnd.VendorTypeID == 4 || vnd.VendorTypeID == 5)
                           && (from restcnf in Restconfirm from grp in Group where restcnf.GroupID == grp.GroupID && restcnf.StatusID == vnSt.StatusID select restcnf.VendorID).Contains(vnd.VendorID)
                           group vnd by new { vnd.VendorID, vnd.VendorName } into grp
                           orderby grp.Key.VendorName
                           select new { Key = grp.Key.VendorID, Value = grp.Key.VendorName }).ToDictionary(o => o.Key, o => o.Value);
            foreach (var name in RestName)
            {
                if (!(AttName.Keys.Contains(name.Key)))
                    AttName.Add(name.Key, name.Value);
            }
            AttractionsData.FilterVendorName = AttName.OrderBy(name => name.Key).ToDictionary(name => name.Key, name => name.Value);
            // Filter Vendor City init
            var AttCity = (from vnd in _context.tblVendors
                           from vnSt in _context.tblVConfirmStatus
                           where vnd.Active == true && vnSt.Active == true
                           && (vnd.VendorTypeID == 2 || vnd.VendorTypeID == 4 || vnd.VendorTypeID == 5)
                           && vnd.City != null
                           && vnd.City.Length > 2
                           && (from attrconf in Attrconfirm from grp in Group where attrconf.GroupID == grp.GroupID && attrconf.StatusID == vnSt.StatusID select attrconf.VendorID).Contains(vnd.VendorID)
                           group vnd by new { vnd.City } into grp
                           orderby grp.Key.City
                           select grp.Key.City).ToList();
            var RestCity = (from vnd in _context.tblVendors
                           from vnSt in _context.tblVConfirmStatus
                           where vnd.Active == true && vnSt.Active == true
                           && (vnd.VendorTypeID == 2 || vnd.VendorTypeID == 4 || vnd.VendorTypeID == 5)
                           && vnd.City != null
                           && vnd.City.Length > 2
                           && (from restcnf in Restconfirm from grp in Group where restcnf.GroupID == grp.GroupID && restcnf.StatusID == vnSt.StatusID select restcnf.VendorID).Contains(vnd.VendorID)
                           group vnd by new { vnd.City } into grp
                           orderby grp.Key.City
                           select grp.Key.City).ToList();
            foreach (var city in RestCity)
            {
                if (!(AttCity.Any(acity => acity == city)))
                    AttCity.Add(city);
            }
            AttractionsData.FilterVendorCity.AddRange(AttCity.OrderBy(city=>city));
            // Filter RestaurantType init
            AttractionsData.FilterRestaurantType = (from rest in Restconfirm
                                                    from vnd in _context.tblVendors
                                                    from vnSt in _context.tblVConfirmStatus
                                                    where vnd.Active == true && vnSt.Active == true
                                                    && rest.VendorID == vnd.VendorID && vnSt.StatusID == rest.StatusID
                                                    group rest by new { rest.Category } into grp
                                                    orderby grp.Key.Category
                                                    select grp.Key.Category).ToList();
            //Filter Vendor Name init
            AttractionsData.FilterVendorType = (from vndtype in _context.tblVendorTypes
                                                where vndtype.Active == true
                                                && (vndtype.VendorTypeID == 2 || vndtype.VendorTypeID == 4)
                                                group vndtype by new { vndtype.VendorTypeID, vndtype.VendorTypeCode } into grp
                                                orderby grp.Key.VendorTypeCode
                                                select new { Key = grp.Key.VendorTypeID, Value = grp.Key.VendorTypeCode }).ToDictionary(o => o.Key, o => o.Value);
        }
        private void InitOperationMiscGridBData(OperationMiscGridBData MiscData, IQueryable<tblMiscConfirm> Miscconfirm, IQueryable<tblGroup> Group, string UserName)
        {
            MiscData.VendorInfo = new List<OperationMiscVendorInfoBData>();
            MiscData.VendorName = new Dictionary<int, string>();
            MiscData.GroupCode = new Dictionary<int, string>();
            MiscData.Customer = new Dictionary<int, string>();
            MiscData.VendorCity = new List<string>();
            MiscData.VendorStatus = new Dictionary<int, string>();
            MiscData.Employee = new Dictionary<int, string>();
            MiscData.DetailCode = new Dictionary<int, string>();
            MiscData.PayMethod = new Dictionary<int, string>();
            // Employee
            var EmpID = _context.Users.Where(usr => usr.UserName == UserName).Select(usr => usr.EmployeeID).SingleOrDefault();
            var SupEmp = _context.tblSupEmployees.Where(sup => sup.EmployeeID == EmpID).Select(sup => sup.SupervisorID).ToList();
            MiscData.Employee = (from user in _context.Users
                                 from emp in _context.tblEmployees
                                 where user.EmployeeID == emp.EmployeeID && emp.Active == true && SupEmp.Contains((int)user.EmployeeID)
                                 orderby emp.FirstName, emp.LastName
                                 select new
                                 {
                                     Key = emp.EmployeeID,
                                     Value = emp.FirstName + " " + emp.LastName,
                                 }).ToDictionary(o => o.Key, o => o.Value);
            // Detail Code init
            MiscData.DetailCode = (from detail in _context.tblDetails
                                  from DetType in _context.tblDetailTypes
                                  where detail.DetailTypeID == DetType.DetailTypeID
                                  && detail.Active == true
                                  && DetType.Active == true
                                  && DetType.VendorTypeID != 1
                                  orderby detail.DetailCode
                                  select new { Key = detail.DetailID, Value = detail.DetailCode }).ToDictionary(o => o.Key, o => o.Value);
            // vendor status init
            MiscData.VendorStatus = (from vnSt in _context.tblVConfirmStatus
                                     where vnSt.Active == true
                                     orderby vnSt.StatusID
                                     select new { Key = vnSt.StatusID, Value = vnSt.StatusDesc }).ToDictionary(o => o.Key, o => o.Value);
            // Customer Code init
            MiscData.Customer = (from cust in _context.tblCustomers
                                 where cust.Active == true
                                 && cust.CustomerCode != null
                                 && (from grp in _context.tblGroups select grp.CustomerID).Contains(cust.CustomerID)
                                 group cust by new { cust.CustomerID, cust.CustomerCode } into grp
                                 orderby grp.Key.CustomerCode
                                 select new { Key = grp.Key.CustomerID, Value = grp.Key.CustomerCode }).ToDictionary(o => o.Key, o => o.Value);
            // pay method init
            MiscData.PayMethod = (from card in _context.tblCards
                                  from cardtype in _context.tblCardTypes
                                  where card.CardTypeID == cardtype.CardTypeID
                                  && card.Active == true
                                  select new { Key = card.CardID, Value = cardtype.CardTypeCode }).ToDictionary(o => o.Key, o => o.Value);
            // Vendor City init
            MiscData.VendorCity = (from vnd in _context.tblVendors
                                   where (vnd.VendorTypeID != 1 && vnd.VendorTypeID != null && vnd.VendorTypeID == 0)
                                   && vnd.Active == true
                                   && vnd.City != null
                                   && vnd.City.Length > 2
                                   && (from miscconf in Miscconfirm select miscconf.VendorID).Contains(vnd.VendorID)
                                   group vnd by new { vnd.City } into grp
                                   orderby grp.Key.City
                                   select grp.Key.City).ToList();
            // Vendor Info init
            MiscData.VendorInfo = (from vnd in _context.tblVendors
                                   from vndType in _context.tblVendorTypes
                                   where (vnd.VendorTypeID != 1 && vnd.VendorTypeID != null && vnd.VendorTypeID != 0)
                                   && vnd.VendorTypeID == vndType.VendorTypeID
                                   && vnd.Active == true
                                   && vnd.VendorName != null
                                   && vnd.VendorName.Length > 5
                                   select new OperationMiscVendorInfoBData
                                   {
                                       VendorID = vnd.VendorID,
                                       VendorName = vnd.VendorName,
                                       VendorCity = vnd.City,
                                       VendorAddress = vnd.Address,
                                       VendorContactPerson = vnd.ContactName,
                                       VendorEmail = vnd.EmailNameSales,
                                       VendorPhone = vnd.PhoneSales,
                                       IsFind = vnd.IsFind,
                                       VendorType = vndType.VendorTypeCode,
                                   }).ToList();
            // Vendor Name init
            MiscData.VendorName = (from vnd in _context.tblVendors
                                   where (vnd.VendorTypeID != 1 && vnd.VendorTypeID != null && vnd.VendorTypeID != 0)
                                   && vnd.Active == true
                                   && vnd.VendorName != null
                                   && vnd.VendorName.Length > 5
                                   && (from miscconf in _context.tblMiscConfirms select miscconf.VendorID).Contains(vnd.VendorID)
                                   group vnd by new { vnd.VendorID, vnd.VendorName } into grp
                                   orderby grp.Key.VendorName
                                   select new { Key = grp.Key.VendorID, Value = grp.Key.VendorName }).ToDictionary(o => o.Key, o => o.Value);
            // Group Code init
            MiscData.GroupCode = (from grp in _context.tblGroups
                                  where grp.GroupCode != null
                                  && ((from attr in _context.tblAttractionsConfirms select attr.GroupID).Contains(grp.GroupID) || (from restconf in _context.tblRestaurantsConfirms select restconf.GroupID).Contains(grp.GroupID))
                                  group grp by new { grp.GroupID, grp.GroupCode } into attr
                                  orderby attr.Key.GroupCode
                                  select new { Key = attr.Key.GroupID, Value = attr.Key.GroupCode }).ToDictionary(o => o.Key, o => o.Value);
            //Filter Group Code init
            MiscData.FilterGroupCode = (from grp in Group
                                        where grp.GroupCode != null
                                        orderby grp.GroupCode
                                        select new { Key = grp.GroupID, Value = grp.GroupCode }).ToDictionary(o => o.Key, o => o.Value);
            //Filter Group Name init
            MiscData.FilterGroupName = (from grp in Group
                                        where grp.GroupName != null
                                        orderby grp.GroupName
                                        select new { Key = grp.GroupID, Value = grp.GroupName }).ToDictionary(o => o.Key, o => o.Value);
            //Filter Customer Code init
            MiscData.FilterCustomerCode = (from cust in _context.tblCustomers
                                                  where cust.Active == true
                                                  && cust.OrganizationName != null
                                                  && (from grp in Group select grp.CustomerID).Contains(cust.CustomerID)
                                                  group cust by new { cust.CustomerID, cust.OrganizationName } into grp
                                                  orderby grp.Key.OrganizationName
                                                  select new { Key = grp.Key.CustomerID, Value = grp.Key.OrganizationName }).ToDictionary(o => o.Key, o => o.Value);
            // Filter vendor status init
            MiscData.FilterVendorStatus = (from vnSt in _context.tblVConfirmStatus
                                           from grp in Group
                                           from misccnf in Miscconfirm
                                           where (misccnf.GroupID == grp.GroupID && misccnf.StatusID == vnSt.StatusID)
                                           && vnSt.Active == true
                                           group vnSt by new { vnSt.StatusID, vnSt.StatusDesc } into grp
                                           orderby grp.Key.StatusID
                                           select new { Key = grp.Key.StatusID, Value = grp.Key.StatusDesc }).ToDictionary(o => o.Key, o => o.Value);
            //Filter Vendor Name init
            MiscData.FilterVendorName = (from vnd in _context.tblVendors
                                         from vnSt in _context.tblVConfirmStatus
                                         where vnd.Active == true && vnSt.Active == true
                                         && vnd.VendorName != null
                                         && (vnd.VendorTypeID != 1 && vnd.VendorTypeID != null && vnd.VendorTypeID != 0)
                                         && (from miscconf in Miscconfirm from grp in Group where miscconf.GroupID == grp.GroupID && miscconf.StatusID == vnSt.StatusID select miscconf.VendorID).Contains(vnd.VendorID)
                                         group vnd by new { vnd.VendorID, vnd.VendorName } into grp
                                         orderby grp.Key.VendorName
                                         select new { Key = grp.Key.VendorID, Value = grp.Key.VendorName }).ToDictionary(o => o.Key, o => o.Value);
            // Filter Vendor City init
            MiscData.FilterVendorCity = (from vnd in _context.tblVendors
                                                from vnSt in _context.tblVConfirmStatus
                                                where vnd.Active == true && vnSt.Active == true
                                                && (vnd.VendorTypeID != 1 && vnd.VendorTypeID != null && vnd.VendorTypeID != 0)
                                                && vnd.City != null
                                                && vnd.City.Length > 2
                                                && (from miscconf in Miscconfirm from grp in Group where miscconf.GroupID == grp.GroupID && miscconf.StatusID == vnSt.StatusID select miscconf.VendorID).Contains(vnd.VendorID)
                                                group vnd by new { vnd.City } into grp
                                                orderby grp.Key.City
                                                select grp.Key.City).ToList();
        }
        private void OperationBusFiltersInit(ref IQueryable<tblGroup> FilterGroup, ref IQueryable<tblVendor> FilterVendor, ref IQueryable<tblGuide> FilterGuide, ref IQueryable<tblBusConfirm> FilterBusConfirm, ref IQueryable<tblGuideConfirm> FilterGuideConfirm, OperationBusFilterBData Data)
        {
            // filtering Bus Status
            if (Data.FilterBusStatusVal != null)
                FilterBusConfirm = FilterBusConfirm.Where(vconf => Data.FilterBusStatusVal.Contains(vconf.StatusID));
            // filtering Bus Status
            if (Data.FilterBusStartCityVal != null)
                FilterBusConfirm = FilterBusConfirm.Where(vconf => Data.FilterBusStartCityVal.Contains(vconf.StartCity));
            // filtering Bus Status
            if (Data.FilterBusEndCityVal != null)
                FilterBusConfirm = FilterBusConfirm.Where(vconf => Data.FilterBusEndCityVal.Contains(vconf.EndCity));
            // filtering Bus Group Code
            if (Data.FilterBusGroupCodeVal != null)
                FilterGroup = FilterGroup.Where(grp => Data.FilterBusGroupCodeVal.Contains(grp.GroupID));
            // filtering Bus Group Name
            if (Data.FilterBusGroupNameVal != null)
                FilterGroup = FilterGroup.Where(grp => Data.FilterBusGroupNameVal.Contains(grp.GroupID));
            // filtering Customer Code
            if (Data.FilterBusCustomerCodeVal != null)
                FilterGroup = FilterGroup.Where(grp => Data.FilterBusCustomerCodeVal.Contains(grp.CustomerID));
            // filtering Vendor Name
            if (Data.FilterBusVendorNameVal != null)
                FilterBusConfirm = FilterBusConfirm.Where(vconf => Data.FilterBusVendorNameVal.Contains(vconf.VendorID));
        }
        private List<OperationBusGridRowBData> InitBusGridBData(int PageNum, IQueryable<tblGroup> Group, IQueryable<tblCustomer> Customer, IQueryable<tblGuideConfirm> GuideConfirm, IQueryable<tblVendor> Vendor, IQueryable<tblBusConfirm> BusConfirm, List<string> UserRegions, string UserName, ref int Count)
        {
            var Rows = new List<OperationBusGridRowBData>();
            // Employee
            var EmpID = _context.Users.Where(usr => usr.UserName == UserName).Select(usr => usr.EmployeeID).SingleOrDefault();
            Count = (from Grp in Group
                     from Cust in Customer
                     from quota in _context.tblQuotations
                     from BusConf in BusConfirm
                     from Vnd in Vendor
                     from VndType in _context.tblVendorTypes
                     from VndStatus in _context.tblVConfirmStatus
                     where Grp.QuotaID == quota.QuotaID && UserRegions.Contains(quota.Region)
                     && BusConf.GroupID == Grp.GroupID
                     && Cust.CustomerID == Grp.CustomerID && Cust.Active == true
                     && Vnd.VendorID == BusConf.VendorID && Vnd.Active == true
                     && Vnd.VendorTypeID == VndType.VendorTypeID
                     && BusConf.StatusID == VndStatus.StatusID && VndStatus.Active == true
                     select BusConf.GroupID).Count();
            var BusRows = (from Grp in Group
                           from Cust in Customer
                           from quota in _context.tblQuotations
                           from BusConf in BusConfirm
                           from Vnd in Vendor
                           from VndType in _context.tblVendorTypes
                           from VndStatus in _context.tblVConfirmStatus
                           where Grp.QuotaID == quota.QuotaID && UserRegions.Contains(quota.Region)
                           && BusConf.GroupID == Grp.GroupID
                           && Cust.CustomerID == Grp.CustomerID && Cust.Active == true
                           && Vnd.VendorID == BusConf.VendorID && Vnd.Active == true
                           && Vnd.VendorTypeID == VndType.VendorTypeID
                           && BusConf.StatusID == VndStatus.StatusID && VndStatus.Active == true
                           orderby BusConf.StartDate
                           select new OperationBusGridRowBData()
                           {
                               GroupID = BusConf.GroupID,
                               VendorSelStatus = VndStatus.StatusDesc,
                               VendorID = BusConf.VendorID,
                               BusStartDate = BusConf.StartDate,
                               BusTime = BusConf.Time,
                               BusFinishDate = BusConf.FinishDate,
                               ConfirmDate = BusConf.ConfirmDate,
                               StatusID = BusConf.StatusID,
                               IsInvoice = BusConf.IsInvoice,
                               InvoicePrice = BusConf.InvoicePrice,
                               QuotaID = Grp.QuotaID,
                               QuotaBusRate = BusConf.QuotaRate,
                               QuotaBusCurr = BusConf.QuotaCurr,
                               QuotaBusSupplier = BusConf.QuotaVendorDesc,
                               GuideID = BusConf.GuideID,
                               GroupCode = Grp.GroupCode,
                               GroupName = Grp.GroupName,
                               QuotaVendorID = BusConf.QuotaVendorID,
                               EmployeeID = _context.tblEmployees.Any(emp=>emp.EmployeeID == BusConf.EmployeeID) ? BusConf.EmployeeID : EmpID,
                               CustomerID = Grp.CustomerID,
                               Customer = Cust.OrganizationName,
                               Cost = BusConf.Cost,
                               NumOfPerson = BusConf.Pax,
                               BusGroupContractPath = BusConf.BusConfirmFile,
                               EstNumOfPerson = Grp.NoOfPerson,
                               BusCount = BusConf.BusCount,
                               Airport = BusConf.Airport,
                               BusSize = BusConf.BusSize,
                               BusPrice = BusConf.BusPrice,
                               ServiceDate = BusConf.ServiceDate,
                               ServiceDetID = BusConf.ServiceDetID,
                               ServiceID = BusConf.ServiceID,
                               StartCity = BusConf.StartCity,
                               EndCity = BusConf.EndCity,
                               FirstPayAmt = BusConf.FirstPayment,
                               FirstPayMethod = BusConf.FirstPaymentMethod,
                               FirstPayDate = BusConf.FirstPaymentDate,
                               SecondPayAmt = BusConf.SecondPayment,
                               SecondPayMethod = BusConf.SecondPaymentMethod,
                               SecondPayDate = BusConf.SecondPaymentDate,
                               ThirdPayAmt = BusConf.ThirdPayment,
                               ThirdPayMethod = BusConf.ThirdPaymentMethod,
                               ThirdPayDate = BusConf.ThirdPaymentDate,
                               Notes = BusConf.Notes,
                           }).Skip((PageNum - 1) * OperationBusGridBData.TakeCount).Take(OperationBusGridBData.TakeCount).ToList();

            var GroupIdsFromBus = BusRows.Select(bus => bus.GroupID).ToList();
            var AllGroups = Group.ToList();

            var GuideRows = (from Grp in Group
                             from Cust in Customer
                             from GuideConf in GuideConfirm
                             where GuideConf.GroupID == Grp.GroupID
                             && Cust.Active == true
                             && Grp.CustomerID == Cust.CustomerID
                             && GroupIdsFromBus.Contains(GuideConf.GroupID)
                             select new OperationBusGridRowBData()
                             {
                                 GroupID = GuideConf.GroupID,
                                 QuotaGuideRate = GuideConf.QuotaRate,
                                 QuotaGuideMisc = GuideConf.QuotaGuideMisc,
                                 QuotaGuideStepOn = GuideConf.QuotaGuideStepOn,
                                 EmployeeID = _context.tblEmployees.Any(emp => emp.EmployeeID == GuideConf.EmployeeID) ? GuideConf.EmployeeID : EmpID,
                                 QuotaGuideCurr = GuideConf.QuotaCurr,
                                 QuotaGuide = GuideConf.QuotaGuideDesc,
                                 GuideStartDate = GuideConf.StartDate,
                                 GuideTime = GuideConf.Time,
                                 QuotaID = Grp.QuotaID,
                                 GroupCode = Grp.GroupCode,
                                 GroupName = Grp.GroupName,
                                 GuideID = GuideConf.GuideID,
                                 QuotaGuideID = GuideConf.QuotaGuideID,
                                 CustomerID = Grp.CustomerID,
                                 Customer = Cust.OrganizationName,
                                 GuideSalary = GuideConf.Salary,
                                 GuideMisc = GuideConf.GuideMisc,
                                 GuideStepOn = GuideConf.GuideStepOn,
                                 GuideSalaryPaid = GuideConf.SalaryPaid,
                                 GuidePaidAmt = GuideConf.PaidAmt,
                                 GuideAddCharge = GuideConf.AddCharge,
                                 GuideFirstPayAmt = GuideConf.FirstPayment,
                                 GuideFirstPayMethod = GuideConf.FirstPaymentMethod,
                                 GuideFirstPayDate = GuideConf.FirstPaymentDate,
                                 GuideSecondPayAmt = GuideConf.SecondPayment,
                                 GuideSecondPayMethod = GuideConf.SecondPaymentMethod,
                                 GuideSecondPayDate = GuideConf.SecondPaymentDate,
                                 GuideThirdPayAmt = GuideConf.ThirdPayment,
                                 GuideThirdPayMethod = GuideConf.ThirdPaymentMethod,
                                 GuideThirdPayDate = GuideConf.ThirdPaymentDate,
                             }).ToList();

           var VendorIds = BusRows.Select(row => row.VendorID).ToList();
           var QuotaVendorIds = BusRows.Select(row => row.QuotaVendorID).ToList();
           var GuideIds = GuideRows.Select(row => row.GuideID).ToList();
           var QuotaGuideIds = GuideRows.Select(row => row.QuotaGuideID).ToList();
           var Vendors = _context.tblVendors.Where(vnd => (VendorIds.Contains(vnd.VendorID) && vnd.Active == true) || QuotaVendorIds.Contains(vnd.VendorID)).ToList();
           var Guides = _context.tblGuides.Where(guide => (GuideIds.Contains(guide.GuideID) && guide.Active == true) || QuotaGuideIds.Contains(guide.GuideID)).ToList();
           var GrpRooms = _context.tblGroupRooms.Where(GrR => GroupIdsFromBus.Contains(GrR.GroupID)).GroupBy(GrR => GrR.GroupID).Select(GrR => new { GrID = GrR.Key, Pax = (short)GrR.Sum(rm => rm.NoOfPerson) }).ToList();

           foreach (var bus in BusRows)
           {
               var CurGuide = GuideRows.Any(guide => guide.GroupID == bus.GroupID && guide.GuideStartDate == bus.BusStartDate && guide.GuideTime == bus.BusTime) ? GuideRows.Where(guide => guide.GroupID == bus.GroupID && guide.GuideStartDate == bus.BusStartDate && guide.GuideTime == bus.BusTime).FirstOrDefault() : null;
               var BusRow = new OperationBusGridRowBData();
               BusRow.GroupID = bus.GroupID;
               BusRow.VendorSelStatus = bus.VendorSelStatus;
               BusRow.QuotaBusSupplier = bus.QuotaBusSupplier;
               BusRow.QuotaBusCurr = bus.QuotaBusCurr;
               BusRow.QuotaBusRate = bus.QuotaBusRate;
               BusRow.QuotaID = bus.QuotaID;
               BusRow.GroupCode = bus.GroupCode;
               BusRow.GroupName = bus.GroupName;
               BusRow.CustomerID = bus.CustomerID;
               BusRow.EmployeeID = bus.EmployeeID;
               BusRow.Customer = bus.Customer;
               BusRow.BusGroupContractPath = bus.BusGroupContractPath;
               BusRow.VendorID = bus.VendorID;
               BusRow.QuotaVendorID = bus.QuotaVendorID;
               BusRow.BusStartDate = bus.BusStartDate;
               BusRow.BusTime = bus.BusTime;
               BusRow.NumOfPerson = bus.NumOfPerson;
               BusRow.EstNumOfPerson = bus.EstNumOfPerson;
               BusRow.IsInvoice = bus.IsInvoice;
               BusRow.InvoicePrice = bus.InvoicePrice;
               BusRow.BusCount = bus.BusCount;
               BusRow.Airport = bus.Airport;
               BusRow.BusSize = bus.BusSize;
               BusRow.BusPrice = bus.BusPrice;
               BusRow.ServiceDate = bus.ServiceDate;
               BusRow.ServiceDetID = bus.ServiceDetID;
               BusRow.ServiceID = bus.ServiceID;
               BusRow.StartCity = bus.StartCity;
               BusRow.EndCity = bus.EndCity;
               BusRow.FirstPayAmt = bus.FirstPayAmt;
               BusRow.FirstPayMethod = bus.FirstPayMethod;
               BusRow.FirstPayDate = bus.FirstPayDate;
               BusRow.SecondPayAmt = bus.SecondPayAmt;
               BusRow.SecondPayMethod = bus.SecondPayMethod;
               BusRow.SecondPayDate = bus.SecondPayDate;
               BusRow.ThirdPayAmt = bus.ThirdPayAmt;
               BusRow.ThirdPayMethod = bus.ThirdPayMethod;
               BusRow.ThirdPayDate = bus.ThirdPayDate;
               BusRow.Notes = bus.Notes;
               if (Vendors.Any(vnd => vnd.VendorID == bus.VendorID && vnd.Active == true))
                   BusRow.Supplier = Vendors.Where(vnd => vnd.VendorID == bus.VendorID).SingleOrDefault().VendorName;

               short Pax = GrpRooms.Where(Rm => Rm.GrID == BusRow.GroupID).Select(Rm => Rm.Pax).SingleOrDefault();
               if (BusRow.IsInvoice == false || BusRow.NumOfPerson == null)
               {
                   if (BusRow.NumOfPerson == null || BusRow.NumOfPerson == 0)
                       BusRow.NumOfPerson = Pax == 0 ? AllGroups.Where(grp => grp.GroupID == BusRow.GroupID).Select(grp => grp.NoOfPerson).SingleOrDefault() : Pax;
                   else if (BusRow.NumOfPerson > 0 && Pax > 0 && BusRow.NumOfPerson != Pax)
                       BusRow.NumOfPerson = Pax;
               }

               if (CurGuide != null)
               {
                   BusRow.GuideStartDate = CurGuide.GuideStartDate;
                   BusRow.GuideTime = CurGuide.GuideTime;
                   BusRow.GuideID = CurGuide.GuideID;
                   BusRow.QuotaGuideID = CurGuide.QuotaGuideID;
                   BusRow.QuotaGuideRate = CurGuide.QuotaGuideRate;
                   BusRow.QuotaGuideMisc = CurGuide.QuotaGuideMisc;
                   BusRow.QuotaGuideStepOn = CurGuide.QuotaGuideStepOn;
                   BusRow.QuotaGuideCurr = CurGuide.QuotaGuideCurr;
                   BusRow.QuotaGuide = CurGuide.QuotaGuide;
                   BusRow.GuideSalary = CurGuide.GuideSalary;
                   BusRow.GuideMisc = CurGuide.GuideMisc;
                   BusRow.GuideStepOn = CurGuide.GuideStepOn;
                   BusRow.GuideSalaryPaid = CurGuide.GuideSalaryPaid;
                   BusRow.GuidePaidAmt = CurGuide.GuidePaidAmt;
                   BusRow.GuideAddCharge = CurGuide.GuideAddCharge;
                   BusRow.GuideFirstPayAmt = CurGuide.GuideFirstPayAmt;
                   BusRow.GuideFirstPayMethod = CurGuide.GuideFirstPayMethod;
                   BusRow.GuideFirstPayDate = CurGuide.GuideFirstPayDate;
                   BusRow.GuideSecondPayAmt = CurGuide.GuideSecondPayAmt;
                   BusRow.GuideSecondPayMethod = CurGuide.GuideSecondPayMethod;
                   BusRow.GuideSecondPayDate = CurGuide.GuideSecondPayDate;
                   BusRow.GuideThirdPayAmt = CurGuide.GuideThirdPayAmt;
                   BusRow.GuideThirdPayMethod = CurGuide.GuideThirdPayMethod;
                   BusRow.GuideThirdPayDate = CurGuide.GuideThirdPayDate;
                   if (Guides.Any(guide => guide.GuideID == CurGuide.GuideID && guide.Active == true))
                   {
                       BusRow.Guide = Guides.Where(guide => guide.GuideID == CurGuide.GuideID).SingleOrDefault().FirstName + " " + Guides.Where(guide => guide.GuideID == CurGuide.GuideID).SingleOrDefault().LastName;
                   }
               }
               Rows.Add(BusRow);
           }
           return Rows;
       }
        private void InitOperationBusGridBData(OperationBusGridBData BusData, IQueryable<tblBusConfirm> BusConfirm, IQueryable<tblGuideConfirm> GuideConfirm, IQueryable<tblGroup> Group, string UserName)
       {
           BusData.VendorInfo = new List<OperationBusVendorInfoBData>();
           BusData.VendorName = new Dictionary<int, string>();
           BusData.GroupCode = new Dictionary<int, string>();
           BusData.Customer = new Dictionary<int, string>();
           BusData.VendorCity = new List<string>();
           BusData.VendorStatus = new Dictionary<int, string>();
           BusData.PayMethod = new Dictionary<int, string>();
           BusData.DetailCode = new Dictionary<int, OperationBusDetailInfoBData>();
           BusData.Service = new List<OperationBusServiceInfoBData>();
           BusData.Employee = new Dictionary<int, string>();
           // Employee
           // Employee
           var EmpID = _context.Users.Where(usr => usr.UserName == UserName).Select(usr => usr.EmployeeID).SingleOrDefault();
           var SupEmp = _context.tblSupEmployees.Where(sup => sup.EmployeeID == EmpID).Select(sup => sup.SupervisorID).ToList();
           BusData.Employee = (from user in _context.Users
                                 from emp in _context.tblEmployees
                                 where user.EmployeeID == emp.EmployeeID && emp.Active == true && SupEmp.Contains((int)user.EmployeeID)
                                 orderby emp.FirstName, emp.LastName
                                 select new
                                 {
                                     Key = emp.EmployeeID,
                                     Value = emp.FirstName + " " + emp.LastName,
                                 }).ToDictionary(o => o.Key, o => o.Value);

           // vendor status init
           BusData.VendorStatus = (from vnSt in _context.tblVConfirmStatus
                                   where vnSt.Active == true
                                   orderby vnSt.StatusID
                                   select new { Key = vnSt.StatusID, Value = vnSt.StatusDesc }).ToDictionary(o => o.Key, o => o.Value);
           // pay method init
           BusData.PayMethod = (from card in _context.tblCards
                                from cardtype in _context.tblCardTypes
                                where card.CardTypeID == cardtype.CardTypeID
                                && card.Active == true
                                select new { Key = card.CardID, Value = cardtype.CardTypeCode }).ToDictionary(o => o.Key, o => o.Value);
           // Customer Code init
           BusData.Customer = (from cust in _context.tblCustomers
                               where cust.Active == true
                               && cust.CustomerCode != null
                               && (from grp in _context.tblGroups select grp.CustomerID).Contains(cust.CustomerID)
                               group cust by new { cust.CustomerID, cust.CustomerCode } into grp
                               orderby grp.Key.CustomerCode
                               select new { Key = grp.Key.CustomerID, Value = grp.Key.CustomerCode }).ToDictionary(o => o.Key, o => o.Value);
           // Vendor City init
           BusData.VendorCity = (from vnd in _context.tblVendors
                                 where (vnd.VendorTypeID == 3)
                                 && vnd.Active == true
                                 && vnd.City != null
                                 && vnd.City.Length > 2
                                 && (from Busconf in BusConfirm select Busconf.VendorID).Contains(vnd.VendorID)
                                 group vnd by new { vnd.City } into grp
                                 orderby grp.Key.City
                                 select grp.Key.City).ToList();
           // Vendor Info init
           BusData.VendorInfo = (from vnd in _context.tblVendors
                                 from vndType in _context.tblVendorTypes
                                 where (vnd.VendorTypeID == 3)
                                 && vnd.VendorTypeID == vndType.VendorTypeID
                                 && vnd.Active == true
                                 && vnd.VendorName != null
                                 && vnd.VendorName.Length > 5
                                 select new OperationBusVendorInfoBData
                                 {
                                     VendorID = vnd.VendorID,
                                     VendorName = vnd.VendorName,
                                     VendorCity = vnd.City,
                                     VendorAddress = vnd.Address,
                                     VendorContactPerson = vnd.ContactName,
                                     VendorEmail = vnd.EmailNameSales,
                                     VendorPhone = vnd.PhoneSales,
                                     IsFind = vnd.IsFind,
                                     VendorType = vndType.VendorTypeCode,
                                 }).ToList();
           // Guide Info init
           BusData.GuideInfo = (from guide in _context.tblGuides
                                where guide.Active == true
                                select new OperationBusGuideInfoBData
                                 {
                                     GuideID = guide.GuideID,
                                     GuideName = guide.FirstName + " " + guide.LastName,
                                 }).ToList();
           // Guide Name init
           BusData.GuideName = (from guide in _context.tblGuides
                                 where guide.Active == true
                                 && (from Guideconf in _context.tblGuideConfirms select Guideconf.GuideID).Contains(guide.GuideID)
                                 group guide by new { guide.GuideID, guide.FirstName, guide.LastName} into grp
                                 orderby grp.Key.FirstName
                                select new { Key = grp.Key.GuideID, Value = grp.Key.FirstName + " " + grp.Key.LastName }).ToDictionary(o => o.Key, o => o.Value);
           // Vendor Name init
           BusData.VendorName = (from vnd in _context.tblVendors
                                 where (vnd.VendorTypeID == 3)
                                 && vnd.Active == true
                                 && vnd.VendorName != null
                                 && vnd.VendorName.Length > 5
                                 && (from Busconf in _context.tblBusConfirms select Busconf.VendorID).Contains(vnd.VendorID)
                                 group vnd by new { vnd.VendorID, vnd.VendorName } into grp
                                 orderby grp.Key.VendorName
                                 select new { Key = grp.Key.VendorID, Value = grp.Key.VendorName }).ToDictionary(o => o.Key, o => o.Value);
           // Detail Code init
           BusData.DetailCode = (from detail in _context.tblDetails
                                 from DetType in _context.tblDetailTypes
                                 where detail.DetailTypeID == DetType.DetailTypeID
                                 && detail.Active == true
                                 && DetType.Active == true
                                 && DetType.VendorTypeID == 3
                                 orderby detail.DetailCode
                                 select new { Key = detail.DetailID, Value = new OperationBusDetailInfoBData { DetailCode = detail.DetailCode, ServiceTypeID = detail.ServiceTypeID } }).ToDictionary(o => o.Key, o => o.Value);
           // Service Init
           BusData.Service = (from srv in _context.tblServices
                              from srvType in _context.tblServiceTypes
                              where srv.ServiceTypeID == srvType.ServiceTypeID && srvType.VendorTypeID == 3
                              orderby srv.ServiceCode
                              select new OperationBusServiceInfoBData { ServiceCode = srv.ServiceCode, ServiceID = srv.ServiceID, ServiceTypeID = srv.ServiceTypeID }).ToList();
            // Group Code init
           BusData.GroupCode = (from grp in _context.tblGroups
                                where grp.GroupCode != null
                                && (from bus in _context.tblBusConfirms select bus.GroupID).Contains(grp.GroupID)
                                group grp by new { grp.GroupID, grp.GroupCode } into bus
                                orderby bus.Key.GroupCode
                                select new { Key = bus.Key.GroupID, Value = bus.Key.GroupCode }).ToDictionary(o => o.Key, o => o.Value);
           //Filter Group Code init
           BusData.FilterGroupCode = (from grp in Group
                                      where grp.GroupCode != null
                                      orderby grp.GroupCode
                                      select new { Key = grp.GroupID, Value = grp.GroupCode }).ToDictionary(o => o.Key, o => o.Value);
           //Filter Group Name init
           BusData.FilterGroupName = (from grp in Group
                                              where grp.GroupName != null
                                              orderby grp.GroupName
                                              select new { Key = grp.GroupID, Value = grp.GroupName }).ToDictionary(o => o.Key, o => o.Value);
           //Filter Customer Code init
           BusData.FilterCustomerCode = (from cust in _context.tblCustomers
                                                 where cust.Active == true
                                                 && cust.OrganizationName != null
                                                 && (from grp in Group select grp.CustomerID).Contains(cust.CustomerID)
                                                 group cust by new { cust.CustomerID, cust.OrganizationName } into grp
                                                 orderby grp.Key.OrganizationName
                                                 select new { Key = grp.Key.CustomerID, Value = grp.Key.OrganizationName }).ToDictionary(o => o.Key, o => o.Value);
           // Filter vendor status init
           BusData.FilterVendorStatus = (from vnSt in _context.tblVConfirmStatus
                                         from grp in Group
                                         from buscnf in BusConfirm
                                         where buscnf.GroupID == grp.GroupID && buscnf.StatusID == vnSt.StatusID
                                         && vnSt.Active == true
                                         group vnSt by new { vnSt.StatusID, vnSt.StatusDesc } into grp
                                         orderby grp.Key.StatusID
                                         select new { Key = grp.Key.StatusID, Value = grp.Key.StatusDesc }).ToDictionary(o => o.Key, o => o.Value);
           //Filter Vendor Name init
           BusData.FilterVendorName = (from vnd in _context.tblVendors
                                       from vnSt in _context.tblVConfirmStatus
                                       where vnd.Active == true && vnSt.Active == true
                                       && vnd.VendorName != null
                                       && vnd.VendorTypeID == 3
                                       && (from buscnf in BusConfirm from grp in Group where buscnf.GroupID == grp.GroupID && buscnf.StatusID == vnSt.StatusID select buscnf.VendorID).Contains(vnd.VendorID)
                                       group vnd by new { vnd.VendorID, vnd.VendorName } into grp
                                       orderby grp.Key.VendorName
                                       select new { Key = grp.Key.VendorID, Value = grp.Key.VendorName }).ToDictionary(o => o.Key, o => o.Value);
           // Filter Start City init
           BusData.FilterStartCity = (from buscnf in BusConfirm
                                      where buscnf.StartCity != null
                                      && buscnf.StartCity.Length > 2
                                      group buscnf by new { buscnf.StartCity } into grp
                                      orderby grp.Key.StartCity
                                      select grp.Key.StartCity).ToList();
           // Filter End City init
           BusData.FilterEndCity = (from buscnf in BusConfirm
                                    where buscnf.EndCity != null
                                    && buscnf.EndCity.Length > 2
                                    group buscnf by new { buscnf.EndCity } into grp
                                    orderby grp.Key.EndCity
                                    select grp.Key.EndCity).ToList();
                                 
       }
        private void OperationGroupCheckListFiltersInit(ref IQueryable<tblGroup> FilterGroup, OperationGroupCheckListFilterBData Data)
        {
            // filtering GroupCheckList Group Code
            if (Data.FilterGroupCheckListGroupCodeVal != null)
                FilterGroup = FilterGroup.Where(grp => Data.FilterGroupCheckListGroupCodeVal.Contains(grp.GroupID));
            // filtering GroupCheckList Group Name
            if (Data.FilterGroupCheckListGroupNameVal != null)
                FilterGroup = FilterGroup.Where(grp => Data.FilterGroupCheckListGroupNameVal.Contains(grp.GroupID));
            // filtering Customer Code
            if (Data.FilterGroupCheckListCustomerCodeVal != null)
                FilterGroup = FilterGroup.Where(grp => Data.FilterGroupCheckListCustomerCodeVal.Contains(grp.CustomerID));
           
        }
        private void InitOperationGroupCheckListGridBData(OperationGroupCheckListGridBData GroupCheckListData, IQueryable<tblGroup> Group, IQueryable<tblCustomer> Customer, string UserName)
        {
            //Filter Group Code init
            GroupCheckListData.FilterGroupCode = (from grp in Group
                                                  where grp.GroupCode != null
                                                  orderby grp.GroupCode
                                                  select new { Key = grp.GroupID, Value = grp.GroupCode }).ToDictionary(o => o.Key, o => o.Value);
            //Filter Group Name init
            GroupCheckListData.FilterGroupName = (from grp in Group
                                                  where grp.GroupName != null
                                                  orderby grp.GroupName
                                                  select new { Key = grp.GroupID, Value = grp.GroupName }).ToDictionary(o => o.Key, o => o.Value);
            //Filter Customer Code init
            GroupCheckListData.FilterCustomerCode = (from cust in _context.tblCustomers
                                                     where cust.Active == true
                                                     && cust.OrganizationName != null
                                                     && (from grp in Group select grp.CustomerID).Contains(cust.CustomerID)
                                                     group cust by new { cust.CustomerID, cust.OrganizationName } into grp
                                                     orderby grp.Key.OrganizationName
                                                     select new { Key = grp.Key.CustomerID, Value = grp.Key.OrganizationName }).ToDictionary(o => o.Key, o => o.Value);

        }
        private List<OperationGroupCheckListGridRowBData> InitGroupCheckListGridBData(int PageNum, IQueryable<tblGroup> Group, IQueryable<tblCustomer> Customer, List<string> UserRegions, string UserName)
        {
            var Rows = new List<OperationGroupCheckListGridRowBData>();

            // Employee
            var EmpID = _context.Users.Where(usr => usr.UserName == UserName).Select(usr => usr.EmployeeID).SingleOrDefault();
            // Main is Group
            Rows = (from grp in Group
                    from quota in _context.tblQuotations
                    from cust in Customer
                    where grp.QuotaID == quota.QuotaID && UserRegions.Contains(quota.Region) 
                    && cust.CustomerID == grp.CustomerID
                    select new OperationGroupCheckListGridRowBData
                    {
                        GroupID = grp.GroupID,
                        GroupCode = grp.GroupCode,
                        GroupName = grp.GroupName,
                        Customer = cust.OrganizationName,
                        ArrivalDate = grp.ArrivalDate,
                        ArrivalCity = grp.ArrivalCity,
                        DepartureDate = grp.DepartureDate,
                        IsGir = grp.IsGir,
                    }).Take(PageNum * OperationGroupCheckListGridBData.TakeCount).ToList();
            var GroupIds = Rows.GroupBy(row => row.GroupID).Select(row => row.Key).ToList();
            var VendConfirms = _context.tblVendorConfirms.Where(VConf => GroupIds.Contains(VConf.GroupID));
            var BusConfirms = _context.tblBusConfirms.Where(BConf => GroupIds.Contains(BConf.GroupID));
            foreach (var row in Rows)
            {
                var VendorConfirm = VendConfirms.Where(vcnf => vcnf.GroupID == row.GroupID).ToList();
                if (VendorConfirm != null && VendorConfirm.Count > 0)
                {
                    row.HotelNotes = string.Join(", ", VendorConfirm.Where(vcnf=>vcnf.Notes != "" && vcnf.Notes != null).Select(vcnf=>vcnf.Notes).ToList());
                    row.HotelStatus = VendorConfirm.Any(vcnf => vcnf.StatusID != 2) ? "Not Made" : "Made";
                }
                else
                {
                    row.HotelNotes = "";
                    row.HotelStatus = "";
                }

                var BusConfirm = BusConfirms.Where(bcnf => bcnf.GroupID == row.GroupID).ToList();
                if (BusConfirm != null && BusConfirm.Count > 0)
                {
                    row.BusGuideNotes = string.Join(", ", BusConfirm.Where(bcnf => bcnf.Notes != "" && bcnf.Notes != null).Select(bcnf => bcnf.Notes).ToList());
                }
                else
                {
                    row.BusGuideNotes = "";
                }
            }
            return Rows;
        }
       private List<OperationTechProgGridRowBData> InitTechProgGridBData(IQueryable<tblGroup> Group, IQueryable<tblTechDetail> TechProg)
       {
           List<OperationTechProgGridRowBData> Rows = new List<OperationTechProgGridRowBData>();
           Rows = (from techDet in TechProg
                   from grp in Group
                   from Det in _context.tblDetails
                   from Emp in _context.tblEmployees
                   where techDet.GroupID == grp.GroupID && techDet.EmployeeID == Emp.EmployeeID
                   && techDet.DetailID == Det.DetailID
                   && Det.Active == true
                   orderby techDet.Date, techDet.Time
                   select new OperationTechProgGridRowBData()
                   {
                       VendorID = techDet.VendorID,
                       GroupID = techDet.GroupID,
                       GuideID = techDet.GuideID,
                       Detail = Det.DetailCode + " - " + Det.DetailDescription,
                       DetailID = techDet.DetailID,
                       Date = techDet.Date,
                       Time = techDet.Time,
                       Desc = techDet.Description,
                       Via = techDet.Via,
                       City = techDet.City,
                       TechProgTypeID = techDet.TechTypeID,
                       Type = techDet.Type,
                       PrnFlag = techDet.PrnFlg,
                       Employee = Emp.FirstName + " " + Emp.LastName,
                   }).ToList();
          

           var VendIds = Rows.Select(row => row.VendorID).ToList();
           var GuideIds = Rows.Select(row => row.GuideID).ToList();
           var Guides = _context.tblGuides.Where(guide => GuideIds.Contains(guide.GuideID)).ToList();
           var Vendors = _context.tblVendors.Where(vnd => VendIds.Contains(vnd.VendorID)).ToList();
           var RegionIds = Vendors.GroupBy(Vnd=>Vnd.RegionID).Select(Vnd=>Vnd.Key).ToList();
           var Areas = _context.tblAreas.Where(area=>RegionIds.Contains((short)area.RegionID)).ToList();
           foreach (var row in Rows)
           {
               var Guide = Guides.Where(guide => guide.GuideID == row.GuideID).SingleOrDefault();
               if (Guide != null)
               {
                   row.Guide = Guide.FirstName + " " + Guide.LastName;
                   row.GuidePhone = Guide.Phone;
               }
               var Vendor = Vendors.Where(vnd => vnd.VendorID == row.VendorID).SingleOrDefault();
               if (Vendor != null)
               {
                   row.Vendor = Vendor.VendorName;
                   row.VendorAddress = Vendor.Address + " " + Vendor.City + " " + Vendor.StateID + " " + Vendor.PostalCode + " ";
                   //country also should be added  +Vendor.co;
                   row.VendorEmail = Vendor.EmailNameSales;
                   row.Area = Vendor.VendorTypeID == 1 ? (Areas.Any(area => area.AreaID == Vendor.AreaID) ? Areas.Where(area => area.AreaID == Vendor.AreaID).Select(area => area.AreaDesc).SingleOrDefault() : "") : "";
               }
           }
           return Rows;
       }
       private void InitOperationTechProgGridBData(OperationTechProgGridBData TechProgBData, IQueryable<tblGroup> Groups, IQueryable<tblTechDetail> TechDetail)
        {
            TechProgBData.TechProgDetails = (from Det in _context.tblDetails
                                             where Det.Active == true
                                             select new
                                             {
                                                 Key = Det.DetailID,
                                                 Value = Det.DetailCode + " - " + Det.DetailDescription,
                                             }).ToDictionary(o => o.Key, o => o.Value);
            if (Groups.Count() > 0)
            {
                var Group = Groups.FirstOrDefault();
                if (Groups != null && Group.ArrivalDate != null)
                {
                    TechProgBData.TechUpdated = Group.TechProgUpdt;
                    TechProgBData.TechUpdateDate = Group.TechProgUpdtDate;
                    TechProgBData.GroupArrivalDate = Convert.ToDateTime(Group.ArrivalDate);
                    TechProgBData.GroupID = Group.GroupID;
                }
            }
            
            //Filter Type City init
            TechProgBData.FilterTechProgType = (from Tdet in TechDetail
                                                from grp in Groups
                                                where grp.GroupID == Tdet.GroupID
                                                group Tdet by new { Tdet.Type } into grp
                                                orderby grp.Key.Type
                                                select grp.Key.Type).ToList();
        }
        private List<OperationHotelGridRowBData> InitHotelGridBData(int PageNum, IQueryable<tblGroup> Group, IQueryable<tblCustomer> Customer, IQueryable<tblCountry> Country, IQueryable<tblVendorConfirm> VendorConfirm, IQueryable<tblVendor> Vendor, IQueryable<tblQuotaHotel> Hotel, List<string> UserRegions, string UserName, ref int Count)
        {
            List<OperationHotelGridRowBData> Rows = new List<OperationHotelGridRowBData>();
            // Employee
            var EmpID = _context.Users.Where(usr => usr.UserName == UserName).Select(usr => usr.EmployeeID).SingleOrDefault();
            Count = (from Grp in Group
                    from cust in Customer
                    from Ctry in Country
                    from VConf in VendorConfirm
                    from Vnd in Vendor
                    from GrStatus in _context.tblGroupStatus
                    from VndStatus in _context.tblVConfirmStatus
                    from Quota in _context.tblQuotations
                    where Grp.QuotaID == Quota.QuotaID
                    && UserRegions.Contains(Quota.Region)
                    && cust.CustomerID == Grp.CustomerID && Ctry.CountryID == Grp.CountryID
                    && VConf.GroupID == Grp.GroupID && VConf.VendorID == Vnd.VendorID
                    && Grp.StatusID == GrStatus.StatusID && VConf.StatusID == VndStatus.StatusID
                    && cust.Active == true && Ctry.Active == true && Vnd.Active == true && VndStatus.Active == true
                    select VConf.GroupID).Count();
            Rows = (from Grp in Group
                    from cust in Customer
                    from Ctry in Country
                    from VConf in VendorConfirm
                    from Vnd in Vendor
                    from GrStatus in _context.tblGroupStatus
                    from VndStatus in _context.tblVConfirmStatus
                    from Quota in _context.tblQuotations
                    where Grp.QuotaID == Quota.QuotaID
                    && UserRegions.Contains(Quota.Region)
                    && cust.CustomerID == Grp.CustomerID && Ctry.CountryID == Grp.CountryID
                    && VConf.GroupID == Grp.GroupID && VConf.VendorID == Vnd.VendorID
                    && Grp.StatusID == GrStatus.StatusID && VConf.StatusID == VndStatus.StatusID
                    && cust.Active == true && Ctry.Active == true && Vnd.Active == true && VndStatus.Active == true
                    orderby VConf.ArrivalDate
                    select new OperationHotelGridRowBData
                    {
                        GroupSelStatus = GrStatus.StatusDesc,
                        VendorSelStatus = VndStatus.StatusDesc,
                        GroupID = Grp.GroupID,
                        VendorID = VConf.VendorID,
                        QuotaID = Grp.QuotaID,
                        GroupCode = Grp.GroupCode,
                        EmployeeID = _context.tblEmployees.Any(emp => emp.EmployeeID == VConf.EmployeeID) ? VConf.EmployeeID : EmpID,
                        Customer = cust.OrganizationName,
                        GroupName = Grp.GroupName,
                        GroupBookedUnder = Grp.BookedUnder,
                        GroupPushedDate = Grp.PushedDate,
                        GroupPushedFileCompDate = Grp.PushDoneDate,
                        EstNumOfPerson = VConf.Pax,
                        ArrivalDate = VConf.ArrivalDate,
                        ArrivalCity = VConf.ArrivalCity,
                        DepartureDate = VConf.DepartureDate,
                        DepartureCity = Grp.DepartureCity,
                        Nationality = Ctry.Nationality,
                        Note = VConf.Notes,
                        VendorName = Vnd.VendorName,
                        VendorAddress = Vnd.Address,
                        VendorContactName = Vnd.ContactName,
                        VendorPhone = Vnd.PhoneSales,
                        VendorEmail = Vnd.EmailNameSales,
                        VendorCity = Vnd.City,
                        Tax = VConf.Tax,
                        Luggage = VConf.Luggage,
                        ABF = VConf.ABF,
                        CBF = VConf.CBF,
                        Lunch = VConf.Lunch,
                        Dinner = VConf.Dinner,
                        LuggageChecked = VConf.LuggageChecked,
                        ABFChecked = VConf.ABFChecked,
                        CBFChecked = VConf.CBFChecked,
                        LunchChecked = VConf.LunchChecked,
                        DinnerChecked = VConf.DinnerChecked,
                        OccTax = VConf.OccTax,
                        Comp = VConf.Comp,
                        TotalCharged = VConf.TotalCharged,
                        Less = VConf.Less,
                        CheckInDate = VConf.ArrivalDate,
                        CheckOutDate = VConf.DepartureDate,
                        EstNumRooms = Grp.Rooms,
                        VendorGroupContractPath = VConf.VendorConfirmFile,
                        QuotaRoom = VConf.QuotaRoom,
                        QuotaTax = VConf.QuotaTax,
                        QuotaOccTax = VConf.QuotaOccTax,
                        QuotaBrk = VConf.QuotaBrk,
                        QuotaLg = VConf.QuotaLg,
                        QuotaNight = VConf.QuotaNight,
                        QuotaVendorName = VConf.QuotaVendorDesc,
                        QuotaCurr = VConf.QuotaCurr,
                        CommissionPerc = VConf.CommissionPerc,
                        CommissionStatus = VConf.CommissionStatus,
                        CommissionRecAmt = VConf.CommissionRecAmt,
                        CommissionRecDate = VConf.CommissionRecDate,
                        CommissionCheckNum = VConf.CommCheckNum,
                        CommissionCheckAmt = VConf.CommCheckAmt,
                        AccountingMemo = VConf.AccMemo,
                        ClientBookingCode = VConf.ClBookingCode,
                        ExtraCost = VConf.ExtraCost,
                        RefFromHotel = VConf.RefFromHotel,
                        TotalHotelInv = VConf.TotInvoice,
                        FirstPayAmt = VConf.FirstPayment,
                        FirstPayMethod = VConf.FirstPaymentMethod,
                        FirstPayDate = VConf.FirstPaymentDate,
                        SecondPayAmt = VConf.SecondPayment,
                        SecondPayMethod = VConf.SecondPaymentMethod,
                        SecondPayDate = VConf.SecondPaymentDate,
                        ThirdPayAmt = VConf.ThirdPayment,
                        ThirdPayMethod = VConf.ThirdPaymentMethod,
                        ThirdPayDate = VConf.ThirdPaymentDate,
                    }).Skip((PageNum - 1) * OperationHotelGridBData.TakeCount).Take(OperationHotelGridBData.TakeCount).ToList();
            var GroupIds = Rows.GroupBy(obj => obj.GroupID).Select(obj => obj.Key).ToList();
            var VendorIds = Rows.GroupBy(obj => obj.VendorID).Select(obj => obj.Key).ToList();
            //var VendorConfRooms = _context.tblVConfirmRooms.Where(vcr => GroupIds.Contains(vcr.GroupID) && VendorIds.Contains(vcr.VendorID)).ToList();
            var VendorConfDet = _context.tblVConfirmDetails.Where(vcd => GroupIds.Contains(vcd.GroupID) && VendorIds.Contains(vcd.VendorID)).OrderBy(vcd => vcd.LineNo).ToList();
            var QuotaIds = Rows.GroupBy(obj => obj.QuotaID).Select(obj => obj.Key).ToList();
            var QuotaHotels = _context.tblQuotaHotels.Where(htl => QuotaIds.Contains(htl.QuotaID)).ToList();
            var QuotaInfos = (from quota in _context.tblQuotations
                              from Contracts in _context.tblContracts
                              where QuotaIds.Contains(quota.QuotaID) && UserRegions.Contains(quota.Region)
                              && quota.Active == true
                              && Contracts.SeasonID == quota.SeasonID
                              select new { SeasonId = quota.SeasonID, QuotaId = quota.QuotaID, ContractPath = Contracts.ContractFile }).ToList();
            List<int> Rms = new List<int> {1,2,3,4,5,79,87};
            foreach (var row in Rows)
            {
                var QuotaInf = QuotaInfos.Where(quota => quota.QuotaId == row.QuotaID).FirstOrDefault();
                var CurVendorConfDet = VendorConfDet.Where(vcd => vcd.GroupID == row.GroupID && vcd.VendorID == row.VendorID).ToList();
                var CurVendorConfDetRms = CurVendorConfDet.Where(CurVc => Rms.Contains((int)CurVc.ServiceID));
                var CurVendorConfDetOther = CurVendorConfDet.Where(CurVc => !Rms.Contains((int)CurVc.ServiceID));
                row.AllSerAmt = CurVendorConfDetRms.Sum(Rm => Rm.Qty * (Rm.Price + Rm.Price * (decimal)row.Tax / 100 + row.OccTax)) + CurVendorConfDetOther.Sum(Oth => Oth.Qty * (Oth.Price));
                if (CurVendorConfDet.Where(vcd => vcd.ServiceID == 1).Count() > 0)
                {
                    row.SglCount = (int)CurVendorConfDet.Where(vcd => vcd.ServiceID == 1).Sum(vcd => vcd.Qty) / CurVendorConfDet.Where(vcd => vcd.ServiceID == 1).Count();
                    row.SglAmt = CurVendorConfDet.Where(vcd => vcd.ServiceID == 1).Sum(vcd => vcd.Price) / CurVendorConfDet.Where(vcd => vcd.ServiceID == 1).Count();
                }
                if (CurVendorConfDet.Where(vcd => vcd.ServiceID == 2).Count() > 0)
                {
                    row.DblCount = (int)CurVendorConfDet.Where(vcd => vcd.ServiceID == 2).Sum(vcd => vcd.Qty) / CurVendorConfDet.Where(vcd => vcd.ServiceID == 2).Count();
                    row.DblAmt = CurVendorConfDet.Where(vcd => vcd.ServiceID == 2).Sum(vcd => vcd.Price) / CurVendorConfDet.Where(vcd => vcd.ServiceID == 2).Count();
                }
                if (CurVendorConfDet.Where(vcd => vcd.ServiceID == 3).Count() > 0)
                {
                    row.TwnCount = (int)CurVendorConfDet.Where(vcd => vcd.ServiceID == 3).Sum(vcd => vcd.Qty) / CurVendorConfDet.Where(vcd => vcd.ServiceID == 3).Count();
                    row.TwnAmt = CurVendorConfDet.Where(vcd => vcd.ServiceID == 3).Sum(vcd => vcd.Price) / CurVendorConfDet.Where(vcd => vcd.ServiceID == 3).Count();
                }
                if (CurVendorConfDet.Where(vcd => vcd.ServiceID == 4).Count() > 0)
                {
                    row.TrpCount = (int)CurVendorConfDet.Where(vcd => vcd.ServiceID == 4).Sum(vcd => vcd.Qty) / CurVendorConfDet.Where(vcd => vcd.ServiceID == 4).Count();
                    row.TrpAmt = CurVendorConfDet.Where(vcd => vcd.ServiceID == 4).Sum(vcd => vcd.Price) / CurVendorConfDet.Where(vcd => vcd.ServiceID == 4).Count();
                }
                if (CurVendorConfDet.Where(vcd => vcd.ServiceID == 5).Count() > 0)
                {
                    row.QudCount = (int)CurVendorConfDet.Where(vcd => vcd.ServiceID == 5).Sum(vcd => vcd.Qty) / CurVendorConfDet.Where(vcd => vcd.ServiceID == 5).Count();
                    row.QudAmt = CurVendorConfDet.Where(vcd => vcd.ServiceID == 5).Sum(vcd => vcd.Price) / CurVendorConfDet.Where(vcd => vcd.ServiceID == 5).Count();
                }
                if (CurVendorConfDet.Where(vcd => vcd.ServiceID == 79).Count() > 0)
                {
                    row.DrvCount = (int)CurVendorConfDet.Where(vcd => vcd.ServiceID == 79).Sum(vcd => vcd.Qty) / CurVendorConfDet.Where(vcd => vcd.ServiceID == 79).Count();
                    row.DrvAmt = CurVendorConfDet.Where(vcd => vcd.ServiceID == 79).Sum(vcd => vcd.Price) / CurVendorConfDet.Where(vcd => vcd.ServiceID == 79).Count();
                }
                if (CurVendorConfDet.Where(vcd => vcd.ServiceID == 87).Count() > 0)
                {
                    row.GudCount = (int)CurVendorConfDet.Where(vcd => vcd.ServiceID == 87).Sum(vcd => vcd.Qty) / CurVendorConfDet.Where(vcd => vcd.ServiceID == 87).Count();
                    row.GudAmt = CurVendorConfDet.Where(vcd => vcd.ServiceID == 87).Sum(vcd => vcd.Price) / CurVendorConfDet.Where(vcd => vcd.ServiceID == 87).Count(); ;
                }

                if (QuotaInf != null)
                    row.VendorContractPath = QuotaInf.ContractPath;
                row.VendorEmail = Helper.IsEmail(row.VendorEmail) ? row.VendorEmail : "";
                row.NumOfPerson = Convert.ToInt16(row.SglCount * OperationRoomPaxByServiceId(1) + row.DblCount * OperationRoomPaxByServiceId(2) + row.TwnCount * OperationRoomPaxByServiceId(3) + row.TrpCount * OperationRoomPaxByServiceId(4) + row.QudCount * OperationRoomPaxByServiceId(5) + row.DrvCount * OperationRoomPaxByServiceId(79) + row.GudCount * OperationRoomPaxByServiceId(87));
            }
            return Rows;
        }
        private void OperationTechProgFiltersInit(ref IQueryable<tblTechDetail> FilterTechDetail, OperationTechProgFilterBData Data)
        {
            // filtering Arrival City
            if (Data.FilterTechProgTypeVal != null)
                FilterTechDetail = FilterTechDetail.Where(tdet => Data.FilterTechProgTypeVal.Contains(tdet.Type));
        }
        private void OperationHotelFiltersInit(ref IQueryable<tblGroup> FilterGroup, ref IQueryable<tblVendor> FilterVendor, ref IQueryable<tblVendorConfirm> FilterVendorConfirm, OperationHotelFilterBData Data)
        {
            // filtering Status
            if (Data.FilterStatusVal != null)
                FilterVendorConfirm = FilterVendorConfirm.Where(vconf => Data.FilterStatusVal.Contains(vconf.StatusID));
            // filtering Group Status
            if (Data.FilterGroupStatusVal != null)
                FilterGroup = FilterGroup.Where(grp => Data.FilterGroupStatusVal.Contains(grp.StatusID));
            // filtering Date of Arrival
            if (Data.FilterDayofArrivalVal != null)
                FilterVendorConfirm = FilterVendorConfirm.Where(grp => Data.FilterDayofArrivalVal.Contains((int)SqlFunctions.DatePart("weekday", grp.ArrivalDate)));
            // filtering Date of Arrival
            if (Data.FilterMonthofArrivalVal != null)
                FilterVendorConfirm = FilterVendorConfirm.Where(grp => Data.FilterMonthofArrivalVal.Contains((int)SqlFunctions.DatePart("Month", grp.ArrivalDate)));
            // filtering Arrival City
            if (Data.FilterArrivalCityVal != null)
                FilterVendorConfirm = FilterVendorConfirm.Where(grp => Data.FilterArrivalCityVal.Contains(grp.ArrivalCity));
            // filtering Estimated Number of Rooms
            if (Data.FilterEstimatedRoomNumberVal != null)
                FilterVendorConfirm = FilterVendorConfirm.Where(vconf => Data.FilterEstimatedRoomNumberVal.Contains((int)vconf.Rooms));
            // filtering Group Code
            if (Data.FilterGroupCodeVal != null)
                FilterGroup = FilterGroup.Where(grp => Data.FilterGroupCodeVal.Contains(grp.GroupID));
            // filtering Group Name
            if (Data.FilterGroupNameVal != null)
                FilterGroup = FilterGroup.Where(grp => Data.FilterGroupNameVal.Contains(grp.GroupID));
            // filtering Customer Code
            if (Data.FilterCustomerCodeVal != null)
                FilterGroup = FilterGroup.Where(grp => Data.FilterCustomerCodeVal.Contains(grp.CustomerID));
            // filtering Vendor Name
            if (Data.FilterVendorNameVal != null)
                FilterVendorConfirm = FilterVendorConfirm.Where(vconf => Data.FilterVendorNameVal.Contains(vconf.VendorID));
            // filtering Vendor City
            if (Data.FilterVendorCityVal != null)
            {
                var VendorIDs = FilterVendor.Where(vnd => Data.FilterVendorCityVal.Contains(vnd.City)).Select(vnd => vnd.VendorID);
                FilterVendorConfirm = FilterVendorConfirm.Where(vconf => VendorIDs.Contains(vconf.VendorID));
            }
        }
        private List<OperationRoomGridRowBData> InitRoomGridBData(int PageNum, IQueryable<tblGroupRoom> Room, IQueryable<tblGroup> Group, IQueryable<tblCustomer> Customer, out List<OperationRoomGirGridRowBData> GirRows,List<string> UserRegions)
        {
            List<OperationRoomGridRowBData> Rows = new List<OperationRoomGridRowBData>();
            GirRows = new List<OperationRoomGirGridRowBData>();

            Rows = (from Rm in Room
                    from Grp in Group
                    from Cust in Customer
                    from quota in _context.tblQuotations
                    where Grp.QuotaID == quota.QuotaID && UserRegions.Contains(quota.Region)
                    && Grp.GroupID == Rm.GroupID
                    && Cust.Active == true
                    && Cust.CustomerID == Grp.CustomerID
                    select new OperationRoomGridRowBData
                    {
                        GroupID = Rm.GroupID,
                        LineNo = Rm.LineNo,
                        GroupName = Grp.GroupName,
                        GroupCode = Grp.GroupCode,
                        // Customer = Rm.CustomerID == null ?  Cust.OrganizationName : _context.tblCustomers.Where(cust=>cust.CustomerID == Rm), 
                        CustomerID = Rm.CustomerID == null ? Cust.CustomerID : (int)Rm.CustomerID,
                        NumOfPerson = Rm.NoOfPerson,
                        ServiceID = Rm.ServiceID,
                        NumOfPersonRoom = Rm.NoOfPersonRoom,
                        Title = Rm.Title,
                        Names = Rm.Names,
                        FullBoard = Rm.FullBoard,
                        FullBoardCount = Rm.FullBoardCount,
                        Notes = Rm.Notes
                    }).ToList();
            //.Take(PageNum * 30).ToList();
            var CustIdList = Rows.Select(row => row.CustomerID).ToList();
            var CustList = _context.tblCustomers.Where(cust => CustIdList.Contains(cust.CustomerID) && cust.Active == true).Select(cust => new { cId = cust.CustomerID, OrgName = cust.OrganizationName }).ToList();
            if (Rows != null)
            {
                foreach (var row in Rows)
                    row.Customer = CustList.Where(cust => cust.cId == row.CustomerID).FirstOrDefault().OrgName;
            }
            var GroupCust = Rows.GroupBy(cust => new { CustID = cust.CustomerID, Cust = cust.Customer }).Select(cust => new { customerName = cust.Key.Cust, customerId = cust.Key.CustID, SSupCount = cust.Sum(pax => pax.NumOfPerson == 1 ? 1 : 0), Pax = cust.Sum(pax => pax.NumOfPerson), FullBCount = cust.Count(Board => Board.FullBoard == true) }).ToList();
            foreach (var cust in GroupCust)
                GirRows.Add(new OperationRoomGirGridRowBData
                {
                    CustomerName = cust.customerName,
                    FullBoardCount = cust.FullBCount,
                    Pax = cust.Pax,
                    SSupCount = cust.SSupCount,
                    CustomerID = cust.customerId,
                });
            return Rows;

        }
        private void InitRoomGirGridBData(ref List<OperationRoomGridRowBData> GirRows)
        {


        }
        private void InitRoomFilters(OperationRoomFilterBData FilterData, ref IQueryable<tblGroupRoom> FilterRoom, ref IQueryable<tblGroup> FilterGroup)
        {
            // filtering Group Name
            if (FilterData.GroupName != null)
                FilterGroup = FilterGroup.Where(grp => grp.GroupName == FilterData.GroupName);
            // filtering Group Code
            if (FilterData.GroupCode != null)
                FilterGroup = FilterGroup.Where(grp => grp.GroupCode == FilterData.GroupCode);
            // filtering customer
            if (FilterData.FilterRoomCustomerVal != null)
                FilterGroup = FilterGroup.Where(grp => FilterData.FilterRoomCustomerVal.Contains(grp.CustomerID));
            // filtering Room Type
            if (FilterData.FilterRoomTypeVal != null)
                FilterRoom = FilterRoom.Where(room => FilterData.FilterRoomTypeVal.Contains(room.ServiceID));
            // filtering Room Title
            if (FilterData.FilterRoomTitleVal != null)
                FilterRoom = FilterRoom.Where(room => FilterData.FilterRoomTitleVal.Contains(room.Title));
        }
        private short OperationRoomPaxByServiceId(int ServiceID)
        {
            if (ServiceID == 1)
                return 1;
            if (ServiceID == 2 || ServiceID == 3)
                return 2;
            if (ServiceID == 4)
                return 3;
            if (ServiceID == 5)
                return 4;
            if (ServiceID == 79 || ServiceID == 87)
                return 0;
            return 0;
        }

        private void InitOperVendorHotelGridBData(ref OperationVendorHotelGridBData VendHotelGrid, ref IQueryable<tblVendorConfirm> VendorConf)
        {
            VendHotelGrid.Rows = new List<OperationVendorHotelGridRowBData>();
            VendHotelGrid.Status = new Dictionary<int, string>();
            try
            {
                VendHotelGrid.Status = (from st in _context.tblVConfirmStatus
                                        where st.Active == true
                                        select new
                                        {
                                            Key = st.StatusID,
                                            Value = st.StatusDesc
                                        }).ToDictionary(o => o.Key, o => o.Value);
                VendHotelGrid.Rows = (from VConf in VendorConf
                                      from Vendor in _context.tblVendors
                                      from Status in _context.tblVConfirmStatus
                                      where Vendor.VendorID == VConf.VendorID 
                                      && Status.StatusID == VConf.StatusID
                                      && Vendor.Active == true
                                      && Status.Active == true
                                      select new OperationVendorHotelGridRowBData()
                                      {
                                          VendorId = VConf.VendorID,
                                          VendorName = Vendor.VendorName,
                                          Status = VConf.StatusID,
                                          StatusSel = Status.StatusDesc,
                                          DepartureDate = VConf.DepartureDate,
                                          ArrivalDate = VConf.ArrivalDate
                                      }).ToList();
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToMessageAndCompleteStacktrace());
            }
        }
        private decimal SingleSupPriceByCurr(string Currency, int? QuotaID)
        {
            int QuotaId = 0;
            if (QuotaID == null)
                return 0;
            else
                QuotaId = Convert.ToInt32(QuotaID);
            QuotationRepository QuotaRep = new QuotationRepository();
            var PriceData = QuotaRep.LoadQuotaCostPriceGrid(QuotaId, null);
            if (Currency == "USD")
                return PriceData.SSupSumFinal;
            else
                return PriceData.SSupSumCadFinal;
        }
        public static decimal? PerPersonPriceByPax(int Pax, string Currency, int? QuotaID)
        {
            int QuotaId = 0;
            if (QuotaID == null)
                return 0;
            else
                QuotaId = Convert.ToInt32(QuotaID);
            QuotationRepository QuotaRep = new QuotationRepository();
            var RowInfo = QuotaRep.LoadQuotaCostPriceGrid(QuotaId, null).Rows;
            var PriceData = RowInfo.Where(row => row.Currency == "US" && Pax >= row.Pax).FirstOrDefault();
            if (PriceData == null)
                PriceData = RowInfo.Where(row => row.Currency == "US" && Pax <= row.Pax).LastOrDefault();
            var PriceDataCad = RowInfo.Where(row => row.Currency == "CA" && Pax >= row.Pax).FirstOrDefault();
            if (PriceDataCad == null)
                PriceDataCad = RowInfo.Where(row => row.Currency == "CA" && Pax <= row.Pax).LastOrDefault();
            if (Currency == "USD" && PriceData != null)
                return PriceData.FPrice;
            if (Currency == "CAD" && PriceDataCad != null)
                return PriceDataCad.FPrice;
            return 0;
        }
        private List<tblVConfirmDetail> UpdateVendorConfirmDetails(List<int> VendorId, int GroupID, List<tblVConfirmRoom> ChangableConfRooms, List<tblVendorConfirm> VendConfirm)
        {
            var VendorConfirmDetails = _context.tblVConfirmDetails.Where(VcDet => VendorId.Contains(VcDet.VendorID) && VcDet.GroupID == GroupID).ToList();
            var VConfRoomGrouped = ChangableConfRooms.GroupBy(Vroom => new { VendorID = Vroom.VendorID, ServiceID = Vroom.ServiceID, GroupID = Vroom.GroupID, ArrivalDate = Vroom.ArrivalDate }).Select(Vroom => new { VendorID = Vroom.Key.VendorID, GroupId = Vroom.Key.GroupID, ArrivalDate = Vroom.Key.ArrivalDate, ServiceID = Vroom.Key.ServiceID, LineNo = Vroom.Max(Rm => Rm.LineNo), ServiceCount = Vroom.Count(Rm => Rm.ServiceID > 0) }).ToList();
            Dictionary<int, int> LineNos = VendorConfirmDetails.GroupBy(RoomDet => RoomDet.VendorID).Select(RoomDet => new { Key = RoomDet.Key, Value = RoomDet.Max(det => det.LineNo) }).ToDictionary(o => o.Key, o => o.Value);
            var RoomSerIds = new List<int?> { 1, 2, 3, 4, 5, 79, 87 };
            var OtherSerIds = new List<int?> { 6, 7, 70, 71, 103 };
            var VendorConfirmDetailsRoomService = VendorConfirmDetails.Where(Vcd => RoomSerIds.Contains(Vcd.ServiceID)).ToList();
            var VendorConfirmDetailsOtherService = VendorConfirmDetails.Where(Vcd => OtherSerIds.Contains(Vcd.ServiceID)).ToList();
            foreach (var ConfDetRm in VendorConfirmDetailsRoomService)
                ConfDetRm.Qty = 0;
           
            foreach (var VConfRm in VConfRoomGrouped)
            {
                var VendorConfirmDets = VendorConfirmDetails.Where(VcDet => VcDet.VendorID == VConfRm.VendorID && VcDet.ServiceID == VConfRm.ServiceID && VcDet.GroupID == VConfRm.GroupId && VcDet.ArrivalDate == VConfRm.ArrivalDate).ToList();
                if (VendorConfirmDets.Count != 0)
                {
                    var Pax = ChangableConfRooms.Where(room => room.VendorID == VConfRm.VendorID).Sum(room => room.NoOfPerson);
                    var VConfSerOtherDet = VendorConfirmDetailsOtherService.Where(VConfDet => VConfDet.VendorID == VConfRm.VendorID);
                    foreach (var OtherDet in VConfSerOtherDet)
                        OtherDet.Qty = (short)Pax;
                    foreach (var Det in VendorConfirmDets)
                        Det.Qty = Convert.ToInt16(VConfRm.ServiceCount);
                }
                else if (LineNos.Keys.Contains(VConfRm.VendorID))
                {
                    var VndConf = VendConfirm.Where(Vc => Vc.VendorID == VConfRm.VendorID && Vc.ArrivalDate == VConfRm.ArrivalDate).SingleOrDefault();
                    if (VndConf != null && VndConf.DepartureDate != null)
                    {
                        int Days = (Convert.ToDateTime(VndConf.DepartureDate) - VndConf.ArrivalDate).Days;
                        for (int ind = 1; ind <= Days; ind++)
                        {
                            LineNos[VConfRm.VendorID]++;
                            tblVConfirmDetail NewVendConfDet = new tblVConfirmDetail()
                            {
                                VendorID = VConfRm.VendorID,
                                GroupID = VConfRm.GroupId,
                                ArrivalDate = VConfRm.ArrivalDate,
                                LineNo = LineNos[VConfRm.VendorID],
                                ServiceID = VConfRm.ServiceID,
                                Qty = Convert.ToInt16(VConfRm.ServiceCount),
                                StartDate = VConfRm.ArrivalDate.AddDays(ind - 1),
                                EndDate = VConfRm.ArrivalDate.AddDays(ind),
                            };
                            _context.tblVConfirmDetails.Add(NewVendConfDet);
                        }
                    }
                }

            }
            return VendorConfirmDetails;
        }
        private void UpdateVendorConfirmDetailsNew(List<int> VendorId, int GroupID, List<tblVConfirmDetail> VendorConfirmDetails, List<tblVConfirmRoom> ChangableConfRooms, List<tblVendorConfirm> VendConfirm)
        {
            var VConfRoomGrouped = ChangableConfRooms.GroupBy(Vroom => new { VendorID = Vroom.VendorID, ServiceID = Vroom.ServiceID, GroupID = Vroom.GroupID, ArrivalDate = Vroom.ArrivalDate }).Select(Vroom => new { VendorID = Vroom.Key.VendorID, GroupId = Vroom.Key.GroupID, ArrivalDate = Vroom.Key.ArrivalDate, ServiceID = Vroom.Key.ServiceID, LineNo = Vroom.Max(Rm => Rm.LineNo), ServiceCount = Vroom.Count(Rm => Rm.ServiceID > 0) }).ToList();
            Dictionary<int, int> LineNos = VendorConfirmDetails.GroupBy(RoomDet => RoomDet.VendorID).Select(RoomDet => new { Key = RoomDet.Key, Value = RoomDet.Max(det => det.LineNo) }).ToDictionary(o => o.Key, o => o.Value);
            var RoomSerIds = new List<int?> { 1, 2, 3, 4, 5, 79, 87 };
            var OtherSerIds = new List<int?> { 6, 7, 70, 71, 103 };
            var VendorConfirmDetailsOtherService = VendorConfirmDetails.Where(Vcd => OtherSerIds.Contains(Vcd.ServiceID)).ToList();
            var VendorConfirmDetailsRoomService = VendorConfirmDetails.Where(Vcd => RoomSerIds.Contains(Vcd.ServiceID)).ToList();
            foreach (var ConfDetRm in VendorConfirmDetailsRoomService)
                ConfDetRm.Qty = 0;
            foreach (var VConfRm in VConfRoomGrouped)
            {
                var VendorConfirmDets = VendorConfirmDetails.Where(VcDet => VcDet.VendorID == VConfRm.VendorID && VcDet.ServiceID == VConfRm.ServiceID && VcDet.GroupID == VConfRm.GroupId && VcDet.ArrivalDate == VConfRm.ArrivalDate).ToList();
                if (VendorConfirmDets.Count != 0)
                {
                    var Pax = ChangableConfRooms.Where(room => room.VendorID == VConfRm.VendorID).Sum(room => room.NoOfPerson);
                    var VConfSerOtherDet = VendorConfirmDetailsOtherService.Where(VConfDet => VConfDet.VendorID == VConfRm.VendorID);
                    foreach (var OtherDet in VConfSerOtherDet)
                        OtherDet.Qty = (short)Pax;
                    foreach (var Det in VendorConfirmDets)
                        Det.Qty = Convert.ToInt16(VConfRm.ServiceCount);
                }

                else if (LineNos.Keys.Contains(VConfRm.VendorID))
                {
                    var VndConf = VendConfirm.Where(Vc => Vc.VendorID == VConfRm.VendorID && Vc.ArrivalDate == VConfRm.ArrivalDate).SingleOrDefault();
                    if (VndConf != null && VndConf.DepartureDate != null)
                    {
                        int Days = (Convert.ToDateTime(VndConf.DepartureDate) - VndConf.ArrivalDate).Days;
                        for (int ind = 1; ind <= Days; ind++)
                        {
                            LineNos[VConfRm.VendorID]++;
                            tblVConfirmDetail NewVendConfDet = new tblVConfirmDetail()
                            {
                                VendorID = VConfRm.VendorID,
                                GroupID = VConfRm.GroupId,
                                ArrivalDate = VConfRm.ArrivalDate,
                                LineNo = LineNos[VConfRm.VendorID],
                                ServiceID = VConfRm.ServiceID,
                                Qty = Convert.ToInt16(VConfRm.ServiceCount),
                                StartDate = VConfRm.ArrivalDate.AddDays(ind - 1),
                                EndDate = VConfRm.ArrivalDate.AddDays(ind),
                            };
                            _context.tblVConfirmDetails.Add(NewVendConfDet);
                        }
                    }
                }

            }
        }
        private void UpdateVendorConfirmDetail(int VendorId, int GroupID, DateTime ArrivalDate, List<tblVConfirmRoom> ChangableConfRooms)
        {
            var VConfRoomGrouped = ChangableConfRooms.GroupBy(Vroom => new { VendorID = Vroom.VendorID, ServiceID = Vroom.ServiceID, GroupID = Vroom.GroupID, ArrivalDate = Vroom.ArrivalDate }).Select(Vroom => new { VendorID = Vroom.Key.VendorID, GroupId = Vroom.Key.GroupID, ArrivalDate = Vroom.Key.ArrivalDate, ServiceID = Vroom.Key.ServiceID, LineNo = Vroom.Max(Rm => Rm.LineNo), ServiceCount = Vroom.Count(Rm => Rm.ServiceID > 0) }).ToList();
            var VendorConfirmDetails = _context.tblVConfirmDetails.Where(VcDet => VcDet.VendorID == VendorId && VcDet.GroupID == GroupID).ToList();
            var VendConf = _context.tblVendorConfirms.Where(VConf => VConf.GroupID == GroupID && VConf.VendorID == VendorId && VConf.ArrivalDate == ArrivalDate).SingleOrDefault();
            int LineNo = 0;
            if (VendorConfirmDetails.Count > 0)
                LineNo = VendorConfirmDetails.Max(Vcd => Vcd.LineNo);
            var RoomSerIds = new List<int?> { 1, 2, 3, 4, 5, 79, 87 };
            var OtherSerIds = new List<int?> { 6, 7, 70, 71, 103 };
            var VendorConfirmDetailsOtherService = VendorConfirmDetails.Where(Vcd => OtherSerIds.Contains(Vcd.ServiceID)).ToList();
            var VendorConfirmDetailsRoomService = VendorConfirmDetails.Where(Vcd => RoomSerIds.Contains(Vcd.ServiceID)).ToList();
            foreach (var ConfDetRm in VendorConfirmDetailsRoomService)
                ConfDetRm.Qty = 0;
            foreach (var VConfRm in VConfRoomGrouped)
            {
                var VendorConfirmDets = VendorConfirmDetails.Where(VcDet => VcDet.VendorID == VConfRm.VendorID && VcDet.ServiceID == VConfRm.ServiceID && VcDet.GroupID == VConfRm.GroupId && VcDet.ArrivalDate == VConfRm.ArrivalDate).ToList();
                if (VendorConfirmDets.Count != 0)
                {
                    var Pax = ChangableConfRooms.Where(room => room.VendorID == VConfRm.VendorID).Sum(room => room.NoOfPerson);
                    foreach (var Det in VendorConfirmDets)
                        Det.Qty = Convert.ToInt16(VConfRm.ServiceCount);
                }
                else if (VendConf != null && VendConf.DepartureDate != null)
                {
                    int Days = (Convert.ToDateTime(VendConf.DepartureDate) - VendConf.ArrivalDate).Days;
                    for (int ind = 1; ind <= Days; ind++)
                    {
                        LineNo++;
                        tblVConfirmDetail NewVendConfDet = new tblVConfirmDetail()
                        {
                            VendorID = VConfRm.VendorID,
                            GroupID = VConfRm.GroupId,
                            ArrivalDate = VConfRm.ArrivalDate,
                            LineNo = LineNo,
                            ServiceID = VConfRm.ServiceID,
                            Qty = Convert.ToInt16(VConfRm.ServiceCount),
                            StartDate = VConfRm.ArrivalDate.AddDays(ind - 1),
                            EndDate = VConfRm.ArrivalDate.AddDays(ind),
                        };
                        _context.tblVConfirmDetails.Add(NewVendConfDet);
                    }                 
                }

            }
        }
        private string GenerateProvideSectionDates(List<tblVConfirmDetail> VConfDet, string Meal)
        {
            StringBuilder Provide = new StringBuilder();
            if (VConfDet.Count == 1 && Meal == "B")
                return null;
            int Ind = 0;
            foreach (var VcDet in VConfDet)
            {
                if (Ind == 0 && Meal == "B")
                {
                    Ind++;
                    continue;
                }
                if (Ind > 0 && Convert.ToDateTime(VConfDet[Ind].StartDate).Month == Convert.ToDateTime(VConfDet[Ind - 1].StartDate).Month)
                    Provide.Append(Convert.ToDateTime(VcDet.StartDate).ToString("dd") + ", ");
                else
                    Provide.Append(Convert.ToDateTime(VcDet.StartDate).ToString("MMM dd") + ", ");
                Ind++;
            }
            return Provide.ToString();
        }

        #endregion
        public void Dispose()
        {
            _context.Dispose();
        }


    }
}
